gpt4 book ai didi

javascript - 在 .forEach 循环中使用 setState 只会运行具有最新状态的回调函数?

转载 作者:行者123 更新时间:2023-11-30 19:56:27 25 4
gpt4 key购买 nike

我有一个包含 ID 列表的 tempAddList,我会将其状态设置到 relInfo 表中并回调 addRelation 函数以提交数据。但是当我运行 onAddClick 例如,如果 tempAddList = [2,3,4]它会使用最新的 setState id 4 但不是 2 和 3 运行 addRelation 3 次。我如何让它为每个单独的 id 运行。

 onAddClick = () => {
this.state.tempAddList.forEach((id) => {
this.setState({
relInfo: {
...this.state.relInfo,
modId: id
}
}, () => this.addRelation());
});
};

addRelation = () => {
EdmApi.insertModifier(this.state.relInfo)
.then(res => console.log(res))
.catch(err => console.log(err));
};

最佳答案

this.statesetState 一起使用是一种反模式。这可能会导致竞争条件,因为状态更新是异步的。这是 updater function 的用例.

多次 setState 调用将导致批量更新,其中 addRelation 会调用最新的更新状态。

解决方法是不批量更新并等待状态更新,例如with await :

async onAddClick = () => {
const setStateAsync = updater => new Promise(resolve => this.setState(updater, resolve));

for (const id of this.state.tempAddList) {
await setStateAsync(state => ({
relInfo: {
...state.relInfo,
modId: id
}
});
this.addRelation();
});
};

一个更好的解决方案是不依赖副作用中的状态更新(addRelation)。 state 的目的是在render 中使用。如果状态更新不影响 View (只会显示最新的 modId 更新),则不需要:

 onAddClick = () => {
let { relInfo } = this.state;
this.state.tempAddList.forEach((id) => {
relInfo = { ...relInfo, modId: id };
this.addRelation(relInfo);
});

this.setState({ relInfo });
};

addRelation = (relInfo) => {
EdmApi.insertModifier(relInfo);
};

如果 modId 没有在 render 中使用,它可以从状态中排除。在这种特定情况下,缺少更新程序功能应该不是问题,因为点击处理程序是异步触发的,它们不太可能通过干扰状态更新而导致竞争条件。

关于javascript - 在 .forEach 循环中使用 setState 只会运行具有最新状态的回调函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53936565/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com