反应:useState 第一次发送空值但不是第二次发送到我的子组件......?

React : useState send empty value the first time but not the second time to my child component...?

我想将 props 传递给我的子组件 PaperGovernment 。我的道具包含一个对象。我的问题是当我尝试 console.log() 我将发送到我的子组件的道具时,我看到两个数组。第一个是空的,第二个是我的数据,如下所示:

你能帮我解决这个问题吗?

const GovernmentId = (props) => {
    let { id } = useParams();

    const { arrayMinistriesInfo } = props;

    const [governmentList, setGovernmentList] = useState([]);

    useEffect(() => {
        axios.get(`http://localhost:3001/GovernmentCreate/byId/${id}`)
            .then((res) => {

                const resData = res.data;

                arrayMinistriesInfo.map((valueMinitries) => {
           
                        Object.keys(resData).map((i) => {
                        
                            if (i === valueMinitries.dataBase) {
                                resData[i][0].icon = valueMinitries.icon
                                resData[i][0].nameMinistry = valueMinitries.nameMinistry

                            }
                        });
                    
                });

                setGovernmentList(resData);
       

            }).catch((err) => {
                console.log(err);
            });
    }, []);
    return (
        <Box>
            Bonjour
            {console.log(governmentList)}
        </Box>
            //<PaperGovernment governmentList={governmentList}/>        
    );
};

试一试

 <Box>
            Bonjour
           {governmentList?.length > 0 && console.log(governmentList)}
        </Box>

这是预期的行为。

const [governmentList, setGovernmentList] = useState([]);

这里设置governmentList为空数组,所以初始值为空数组

如果您想在获取数据后将数组提供给子组件,您可以这样做:

{governmentList.length && <PaperGovernment governmentList={governmentList}/>}
 

这样,你只给子组件不为空的数组。 如果你愿意,你也可以有一个更复杂的逻辑,例如通过在本地状态中存储一个布尔值来告诉你何时获取数组(在 useEffect 中,最后,它看起来像这样:

setGovernmentList(resData);
setFetchIsDone(true);

然后同样的逻辑,你可以把抓取的数组给子组件:

{fetchIsDone && <PaperGovernment governmentList={governmentList}/>}

请注意,在我的第一种方法中,如果它是一个空数组,则不会将数组提供给子组件,因此如果您仍然希望能够将其提供给子组件,即使它是一个空数组,你应该考虑第二种方法