我正在尝试在Modal中更新people
数组。如果用户单击s取消按钮,则当我单击“打开模态”时,它会将State people array设置回其先前的值。
所以基本上我要做的是,当单击“打开模式”按钮时,将人员数组分配给另一个称为cachedPeople this.setState({ visible: true, cachedPeople: this.state.people })
的变量。
“更改Ben的年龄”按钮具有以下功能:
onPress={() => {
const newPeople = [...this.state.people];
newPeople[2].age = 20;
this.setState({
people: newPeople,
});
}}
然后在Cancel上将people数组设置为cachedPeople
this.setState({ visible: false, people: this.state.cachedPeople });
但
this.state.cachedPeople
的值也将成为this.state.people
的更新值,然后单击“取消”按钮,因此不会发生还原,我不知道这是怎么回事。到目前为止,我尝试将其保存在
this.cachedPeople
而不是状态上,但是仍然会发生。这是示例代码的要点:https://gist.github.com/damathryx/4a379d3c8919ee6431ee79b7a58426c9
最佳答案
您必须克隆。人员和cachedPeople指向相同的资源。所以,我会
//not the best way to clone but ...
this.setState({ visible: true, cachedPeople: JSON.parse(JSON.stringify(this.state.people))});
和,
onPress={() => {
const newPeople = [...this.state.people];
newPeople[2].age = 20;
this.setState({
people: newPeople,
cachedPeople: this.state.cachedPeople
});
}}
和,
this.setState({ visible: false, people: this.state.cachedPeople });
请让我知道是否适合您。