简体   繁体   English

为什么 state 变量的值没有更新?

[英]Why value of state variable isn't being updated?

I've got function component with displayProfileID function inside:我有 function 组件与displayProfileID function 里面:

const [comments, setComments] = useState([]);
const [triggerUpdate, setTriggerUpdate] = useState(Math.random());


const displayProfileID = id => {
...
...

  try {
    axios.get(url).then(resp => {
      if (resp.data.status === "success") {
      ...
      ...
      const obj = resp.data.comments; // <-- receiving an array of objects
      setComments(obj);  // <-- changing state value
      setTriggerUpdate(Math.random()); // <-- forcing update of state variables
      console.log(comments);  //  <-- change isn't reflected ???
    }
  });
} catch (e) {
  console.log(e);
}

};

This is the only function I'm having issue with.这是我遇到的唯一 function 问题。 State variable isn't changed despite triggering component rerender with Math.random() .尽管使用Math.random()触发组件重新渲染,但 State 变量并未更改。

Thank you for any pointers.感谢您的任何指点。

setState is not synchronous. setState不是同步的。 The console.log is logging the value before it has changed (or, more accurately, it has not, and will not change, you'll get a new one—possibly—next render). console.log正在记录值更改之前的值(或者,更准确地说,它没有也不会更改,您将获得一个新值——可能——下一次渲染)。

If you are rendering the content then it should update after you call that setState .如果您正在渲染内容,那么它应该在您调用setState后更新。 The setTrigger things seems unnecessary. setTrigger的东西似乎没有必要。

When you say "I've got function in my component", where?当您说“我的组件中有 function”时,在哪里? This is a function component?这是一个 function 组件? Hooks work in function components, not class ones.挂钩适用于 function 组件,而不是 class 组件。 So hopefully this code is in a functional component.所以希望这段代码在一个功能组件中。

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

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