React 不会在 useEffect 上更新状态

时间:2021-01-17 12:58:08

标签: reactjs react-redux

我是 React 新手。谁能解释为什么加载没有更新其值。在控制台上加载是 1

 import React, { useState, useEffect } from "react";
    function App() {
        useEffect(() => {
            hai();
        }, []);
        const [loading, setLoading] = useState(1);
    
        const hai = () => {
            console.log("............");
            setLoading(2);
            console.log(loading);
        };
    
        return <></>;
    }
    
    export default App;

另外如果有两个状态变量,并且重新排列 set 函数,整个应用程序就会中断

const [loading, setLoading]=useState(false)
const [datas, setDatas]=useState([])

//works fine if loading is set second
 const hai = () => {
       setDatas(res) //fetched from external api
       setLoading(true) 

  };
//throws error in applicaton
 const hai = () => {
       setLoading(true) 
       setDatas(res) //fetched from external api
 };


console.log(datas)

1 个答案:

答案 0 :(得分:1)

您正在以错误的方式测试您的加载值,您应该这样做:

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

并从函数 hai 中删除 console.log(loading) 每当您想要访问某个变量的更新值时,请将其放入 useEffect 并将您想要检查的值放入 useEffect 的依赖项数组中。