useState 由于某种原因没有更新?

时间:2021-01-07 11:33:42

标签: reactjs react-native api react-redux axios

当我尝试使用 axios 从我的后端 API 获取一些数据,并在由于某种原因获得结果后设置状态时,状态未更新,当我尝试使用该状态时,它只会显示一个空数组。但有趣的是,当我 console.log(res.data) 时,它会毫无问题地向我显示我的列表数组,所以我猜问题出在 setCategories() 状态函数上。我做错了什么?

const Home = (props) => {
  const [categories, setCategories] = useState([]);
  useEffect(() => {
    getCats();
  }, []);

  const getCats = async () => {
    const data = await axios.get(`${myUrl}/allItems`, {
      withCredentials: true,
    });
    const cats = await data.data;
    console.log(cats); //this one works perfectly
    setCategories(cats);
    console.log(categories) //this one doesn'nt work which means the setState didn't work
  };


  return (
    <>
      <div className="card-div mt-5">
        {categories.map((cat) => {
          <li>{cat.name}</li>;
        })}
      </div>
    </>
  );
};

2 个答案:

答案 0 :(得分:1)

状态是异步设置的,因此数据不会立即更新。这就是为什么您没有在 console.log(categories)

之后立即获得 setCategories(cats); 的输出

这里是 useState 状态更新异步行为的一个小例子:

工作示例链接:stackblitz

import React, { useEffect, useState } from "react";
import "./style.css";
import axios from "axios";
const url = "https://jsonplaceholder.typicode.com/users";
export default function App() {
  const [users, setUsers] = useState([]);

  useEffect(() => {
    axios.get(url).then(result => {
      console.log("1. when data is fetched sucessfully: ", result.data);
      setUsers(result.data);
      console.log("2. Just after setting state: ", users);
    });
  }, []);

  // secons useEffect for logging out upadated todos useState
  useEffect(() => {
    console.log("todos upadated: ", users);
  }, [users]);
  return (
    <div>
      <h1>Hello StackBlitz!</h1>
      <p>Start editing to see some magic happen :)</p>
      {users.map(user => (
        <p>{user.name}</p>
      ))}
    </div>
  );
}

这是上面例子中发生的事情:

enter image description here

可以看到数据获取的流程和状态的异步更新。

答案 1 :(得分:0)

useState 函数是异步的,所以你永远不会在同一个函数中得到新的状态,最好的方法是在另一个函数或 useEffect 中使用它。 示例:

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