NEXT.js:setState()不更新值

gg0vcinb  于 2023-04-11  发布在  其他
关注(0)|答案(1)|浏览(171)

下面是我的React上下文中的两个函数:

const addComponent = (component) => {
    console.log("adding component to readable template");
    setReadableTemplate([...readableTemplate, component]);
  };

  const updateTemplate = (component) => {
    const index = readableTemplate.findIndex((obj) => obj.id == component.id); // gets the index position of the component
    const updatedComponent = Object.assign({}, readableTemplate[index]); // copys component
    updatedComponent.props = component.props; // updates the props property of the component
    const newReadableTemplate = readableTemplate.slice(); // copys the readable template array
    newReadableTemplate[index] = updatedComponent; // updates new readable template array with the updated component
    setReadableTemplate(newReadableTemplate);
    console.log(readableTemplate); // Value is not being updated -- It's printing out old value
  };

在updateTemplate函数中,setState后的console.log打印旧值而不是新值。不知道如何修复这个问题。有什么想法吗?
注意:即使updateTemplate函数运行多次,值也是相同的。所以我不确定async是否与此有关。

wpcxdonn

wpcxdonn1#

readableTemplate的值不会同步更新。setReadableTemplate函数是异步的,因此在调用setReadableTemplate之后,readableTemplate的值可能不会更新,因此要查看更新后的值,可以使用useEffect

console.log(readableTemplate);
}, [readableTemplate]);

相关问题