简体   繁体   English

异步等待调用后,React状态不会更新

[英]React state not updating after async await call

I am using React Hooks and the useEffect to get data from an API. 我正在使用React Hooks和useEffect从API获取数据。 I need to make 2 consecutive calls. 我需要连续2次打电话。 If I console.log the response directly, it shows the correct response, but when I console.log the state, its empty and its not updating. 如果我直接调用console.log响应,它会显示正确的响应,但是当我在console.log状态时,它是空的,而不是更新。 What am I doing wrong? 我究竟做错了什么?

const [describeFields, setDescribeFields] = useState([]);

useEffect(() => {
const fetchData = async () => {
  await axios
    .all([
      axios.get("someUrl"),
      axios.get("someotherUrl")
    ])
    .then(
      axios.spread((result1, result2) => {
        console.log(result1.data.result.fields); //shows correct response
        setDescribeFields(result1.data.result.fields);
        console.log(describeFields);  //shows empty array      
      })
    );
};
fetchData();
}, []);

It will not be displayed just after that if you want to see latest changes just console log before return statement as setState is async your console.log run before then setState 如果你想在return语句之前只看到控制台日志,那么它就不会在那之后显示,因为setState是async你的console.log之前运行的setState

const [describeFields, setDescribeFields] = useState([]);

useEffect(() => {
const fetchData = async () => {
  await axios
    .all([
      axios.get("someUrl")
      axios.get("someotherUrl")
    ])
    .then(
      axios.spread((result1, result2) => {
        console.log(result1.data.result.fields); //shows correct response
        setDescribeFields(result1.data.result.fields);
      })
    );
};
fetchData();
}, []);

console.log(describeFields); //Check here
return(

)


Note : [] array in useEffect means it will run only one time. 注意:useEffect中的[]数组意味着它只会运行一次。 If you want to update as long as variable changes then add it as dependency. 如果要在变量更改时更新,请将其添加为依赖项。

Here is working example : https://codesandbox.io/s/prod-thunder-et83o 以下是工作示例: https//codesandbox.io/s/prod-thunder-et83o

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM