gpt4 book ai didi

javascript - 有没有比 forceUpdate() 更好的解决方案

转载 作者:行者123 更新时间:2023-11-30 13:58:16 25 4
gpt4 key购买 nike

我的组件状态保存的数据(片段)看起来像这样:

[
{
batchId: 1234,
...
jobRowData: [
{
assignmentId: 12345,
isSelected: false,
...
},
{
assignmentId: 12346,
isSelected: false,
...
}
]
},
{
batchId: 1235,
...
jobRowData: [
{
assignmentId: 12347,
isSelected: false,
...
},
{
assignmentId: 12348,
isSelected: false,
...
}
]
}
]

我想更改 isSelected 并使用以下方法进行更改:

handleIsSelectedChangedJob(selectedIdsData){
let jobRowData = this.state.batchRowData.find((x) => {return x.batchId === selectedIdsData.batchId}).jobRowData
let jobRowItemData = jobRowData.find((x) => {return x.assignmentId === selectedIdsData.assignmentId})
jobRowItemData.isSelected = !jobRowItemData.isSelected // do the update
// this.setState({batchRowData: [...this.state.batchRowData]}) // this also works instead of this.forceUpdate()
this.forceUpdate() // how to refresh view according to update 2 lines above ?
}

参数 selectedIdsData 可能看起来像这样:

{assignmentId: 12346, batchId: 1234}

我的问题是:除了执行 this.forceUpdate() 之外,还有其他刷新 View 的方法吗?它上面的注释行也可以完成这项工作,但它对整个状态对象而不是一个更改的属性进行操作。

最佳答案

当然!您永远不应该直接修改状态(通过引用),这正是 handleIsSelectedChangedJob 内部发生的事情。您必须创建一个新状态并调用 setState:

handleIsSelectedChangedJob({assignmentId, batchId}) {
const dataIndex = this.state.batchRowData.findIndex(x => x.batchId === batchId);
const data = this.state.batchRowData[dataIndex];
const itemIndex = data.jobRowData.findIndex(x => x.assignmentId === assignmentId);
const item = data.jobRowData[itemIndex];

const newItem = {...item, isSelected: !item.isSelected};
const newData = {
...data,
jobRowData: [].concat(
data.jobRowData.slice(0, itemIndex),
newItem,
data.jobRowData.slice(1 + itemIndex)
)
};

this.setState({
batchRowData: [].concat(
batchRowData.slice(0, dataIndex),
newData,
batchRowData.slice(1 + dataIndex)
)
});
}

如您所见,它的代码要多得多,但现在它不会改变状态,只会根据需要复制。当然,有很多图书馆可以做到这一点。它仍然不完美,因为读取 this.state 然后调用 this.setState 并不好——使用 this.state(state => diff) 会更安全:

handleIsSelectedChangedJob({assignmentId, batchId}) {
this.setState(state => {
const dataIndex = state.batchRowData.findIndex(x => x.batchId === batchId);
const data = state.batchRowData[dataIndex];

// Same as above...

return {
batchRowData: [].concat(
batchRowData.slice(0, dataIndex),
newData,
batchRowData.slice(1 + dataIndex)
)
};
});
}

关于javascript - 有没有比 forceUpdate() 更好的解决方案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56805345/

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