typescript - 如何让我的页面等到钩子获取所有数据?

我正在构建一个基于 TypeScript 模板的反应应用程序,并且我的一个页面在钩子完成加载之前加载。

我尝试过制作异步等待,但它是一个钩子,效果不佳。

我如何构建一些东西来等待我的钩子完成然后将它加载到页面上?

我的页面:

export function Home(){


    const { topEventsSelected } = useGetTopEvents(3);

    

    return(
        <div className="d-flex flex-column min-vh-100">
            <NavBar/>
                
                <div className="container">
                    <div className="row mt-4 mb-4 gap">
                        <div className="col-md">
                            <div className="card">
                                <div className="sizingt d-flex card-body flex-column align-items-center sizingt">
                                    <h1>TOP Eventos</h1>
                                    {topEventsSelected.map((eventoInfo)=>
                                        moment(eventoInfo.dataFinal).isBefore() || eventoInfo.cancelado === 'Y' ? 
                                            (
                                                console.log()
                                            ):(
                                                <BlueCard props={eventoInfo}/>
                                            )
                                        
                                    )}
                                </div>
                            </div>
                        </div>

这是我的钩子(注意文件是.ts):

export function useGetTopEvents(quant: number){
    const [eventValues, setEventValues] = useState<Evento[]>([]);
    const [topEvents, setTopEvents] = useState<Evento[]>([]);
    const [topEventsSelected, setTopEventsSelected] = useState<Evento[]>([]);
    
    function organizeEvents(){
        //organazing events by confirmed users
        let topAllEvents = []
        for(let organizer of eventValues){
            if(organizer.confirmNumb > 0){
                topAllEvents.push(organizer)
            }
        }
        topAllEvents.sort((a,b) => b.confirmNumb - a.confirmNumb)
        setTopEvents(topAllEvents)

        //organazing events by quantity selected
        let topSelected = topAllEvents;
        topSelected.sort((a,b) => b.confirmNumb - a.confirmNumb).slice(0,3);
        setTopEventsSelected(topSelected);
    }

    useEffect(() =>{
        const eventRef = database.ref(`eventos`);

        eventRef.once('value', evento => {
            //console.log(evento.val())
            const databaseEventos = evento.val();

            const firebaseEvent: FirebaseEventos = databaseEventos ?? {};
            
            const parsedEventos = Object.entries(firebaseEvent).map(([key, value])=>{
                return{
                    id: key,
                    autorID: value.authorID,
                    autorNome: value.authorName,
                    categoria: value.category,
                    dataInicio: value.startDate,
                    dataFinal: value.endDate,
                    titulo: value.title,
                    cancelado: value.canceled,
                    confirmNumb: Object.entries(value.confirmados ?? {}).length
                }
            }) 
            
            //console.log(parsedEventos)
            
            setEventValues(parsedEventos);

            organizeEvents();
        })

    }, [quant])

    return{topEvents, topEventsSelected}
}

回答1

我认为解决方案是在渲染组件上添加条件渲染。在您的自定义钩子中,您可以再添加一个加载状态,然后您可以基于该状态渲染您的组件。

export function useGetTopEvents(quant: number) {

  const [loading,set] = useState<Boolean>(true)

  function organizeEvents() {
    //organazing events by confirmed users
    ...your function
  }

  useEffect(() => {
      ...
      //console.log(parsedEventos)

      setEventValues(parsedEventos);
      setLoading(false) // set the state to false
      organizeEvents();
    });
  }, [quant]);

  return {topEvents, topEventsSelected, loading};

  // also return the loading state so you could use it with your custom hook
}

然后你可以使用加载如下

const { topEventsSelected ,loading} = useGetTopEvents(3);


      return(
        <div className="d-flex flex-column min-vh-100">
            <NavBar/>
                
               {loading ? ...loading : your render login}
)

回答2

最好的方法是有条件地渲染您的回报中的元素。

const [data, setData] = useState(null);

在您的返回方法中

return ({
data : <>Your component</> ? <LoadingState />
})

回答3

对其进行故障排除我意识到代码将数据分配给方法 setEventValues(parsedEventos); 上的参数需要更长的时间,因此,由于它是一个多线程,它在完成将数据分配给 setEventValues 之前开始运行 organizeEvents()

通过函数参数发送数据来解决这个问题: organizeEvents(parsedEventos) 然后处理信息并将其保存在 consts 中。

我还将组织事件更改为异步,以避免损坏

这是钩子的最终代码:

export function useGetTopEvents(quant: number){
    
    const [topEvents, setTopEvents] = useState<Evento[]>([]);
    const [topEventsSelected, setTopEventsSelected] = useState<Evento[]>([]);

    const [loading, setLoading] = useState(true)
    
    async function organizeEvents(eventValues: Evento[]){
        //organazing events by confirmed users

        let topAllEvents:Evento[] = <Evento[]>[];

        await eventValues.forEach(element =>{
            if(element.confirmNumb > 0){
                topAllEvents.push(element)
            }
        })

        await topAllEvents.sort((a,b) => b.confirmNumb - a.confirmNumb)
        await setTopEvents(topAllEvents)

        //organazing events by quantity selected
        let topSelected = topAllEvents;
        await topSelected.sort((a,b) => b.confirmNumb - a.confirmNumb).slice(0,3);
        await setTopEventsSelected(topSelected);
        
        await setLoading(false)
        
    }

    useEffect(() =>{
        const eventRef = database.ref(`eventos`);

        eventRef.once('value', evento => {
            //console.log(evento.val())
            const databaseEventos = evento.val();

            const firebaseEvent: FirebaseEventos = databaseEventos ?? {};
            
            const parsedEventos = Object.entries(firebaseEvent).map(([key, value])=>{
                return{
                    id: key,
                    autorID: value.authorID,
                    autorNome: value.authorName,
                    categoria: value.category,
                    dataInicio: value.startDate,
                    dataFinal: value.endDate,
                    titulo: value.title,
                    cancelado: value.canceled,
                    confirmNumb: Object.entries(value.confirmados ?? {}).length
                }
            }) 
            
            //console.log(parsedEventos)
            
            organizeEvents(parsedEventos);
            
        })

    }, [quant])

    return{topEvents, topEventsSelected, loading}
}

相似文章

最新文章