下面是我的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是否与此有关。
1条答案
按热度按时间wpcxdonn1#
readableTemplate
的值不会同步更新。setReadableTemplate
函数是异步的,因此在调用setReadableTemplate
之后,readableTemplate
的值可能不会更新,因此要查看更新后的值,可以使用useEffect