状态未在使用效果中更新 ||正在获取数据但未更新状态 ||在本地它正在获取数据并在没有钩子的情况下进行更新

State is not updating in use-effect || data is being fetch but not update state || locally it's fetching data and update without hooks

什么时候显示 console.log() 项目结果,但是当我控制日志数据状态时,它只显示带有空项目数组的初始状态(数据)

  const [data, setdata] = useState({
    projects: []
  });

  useEffect(() => {
   const fetchData = async () => {
    const res = await axios('http://localhost:5000/api/projects');
    const projects = await res.data;
    setdata({ projects: projects });
    console.log(data);
  };
  fetchData();
 }, []);

data 还没有初始化,useEffectrender 生命周期之后运行,所以这样的日志记录是没有用的。

无论如何,状态应该更新,你只是没有检查"if the state is updated"正确。

const [data, setdata] = useState({
    projects: []
  });

  useEffect(() => {
   const fetchData = async () => {
    const res = await axios('http://localhost:5000/api/projects');
    const projects = await res.data;
    setdata({ projects: projects });
    //           v Always results { projects: [] }
    console.log(data);
  };
  fetchData();
 }, []);
axios('http://localhost:5000/api/projects')
.then(res => {
 const projects = res.data
 setdata({ projects: projects })
})