簡體   English   中英

如何將db中的數據設置為reducer初始state?

[英]How to set the data from db to the reducer initial state?

我有一個功能組件,它需要從父組件接收參數(即props.rosterMonth ),然后從數據庫中檢索數據,最后將結果傳遞給子組件。

我的問題是,如何為子組件設置初始 state?

import {useEffect,useReducer} from 'react';
import Roster from '../../../utils/Roster';
import RosterWebContext from '../../../utils/RosterWebContext';
import Testing from './Testing';
export default function VVTable(props){
    let dataReducer=(state,action)=>{
        switch (action.type){
            case 'updateRosterMonth':
                return action.value;
            default:return state;     
        }
    }
    const [contextValue, updateContext] = useReducer(dataReducer,{});
    useEffect(()=>{
        const getData = async () => {
            console.log("Undo:Get Data from DB");
            let roster = new Roster();
            let rosterList= await roster.get(props.rosterMonth.getFullYear(),props.rosterMonth.getMonth()+1);
            updateContext(
                {
                    type:'updateRosterMonth',
                    value:{rosterList}
                }
            );        
        }
        getData();
    },[props]);
    return(
        <table id="rosterTable">
            <RosterWebContext.Provider value={[contextValue, updateContext]}>
                <Testing/>
            </RosterWebContext.Provider>
        </table>    
    )
}   

這是Testing組件。

import {useContext,useEffect} from 'react';
import RosterWebContext from '../../../utils/RosterWebContext';
export default function Testing(props){
    let [contextValue,updateContext]=useContext(RosterWebContext);
    useEffect(()=>{
        console.log(contextValue.rosterList);
    },[contextValue])
    return(
        <tbody>
        </tbody>
    )
}

Currently, I set the initial state to an empty object, so the child component 'Testing' may receive an empty object, to prevent the undefined object error, I need to write some code to check the incoming context value. 如果我可以將數據庫值設置為初始 state,我可以刪除那些檢查代碼。

數據庫中的數據總是會延遲,因為它必須通過來自服務器的 API 調用來檢索(除非您正在執行服務器端渲染)。 所以你必須處理一開始你沒有名單的事實。

在這種情況下,我要做的是檢查是否定義了contextvalue.rosterList以及它是否沒有向用戶顯示一個很好的加載微調器,如下所示:

import {useContext,useEffect} from 'react';
import RosterWebContext from '../../../utils/RosterWebContext';
export default function Testing(props){
    let [contextValue,updateContext]=useContext(RosterWebContext);

    useEffect(()=>{
        console.log(contextValue.rosterList);
    },[contextValue])

    return(
        !!contextValue.rosterList?(
          <tbody>
          </tbody>
        ):(
        <span>Loading Roster</span>
       )
    )
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM