我正在尝试更新模态中的people
数组。如果用户单击s取消按钮,当我单击“打开模态”时,它会将StateState数组设置回其先前的值。
所以基本上我所做的就是在点击Open Modal按钮时将people数组分配给另一个名为cachedPeople this.setState({ visible: true, cachedPeople: this.state.people })
的变量。
"改变Ben的年龄“按钮有这个onPress:
onPress={() => {
const newPeople = [...this.state.people];
newPeople[2].age = 20;
this.setState({
people: newPeople,
});
}}
并在取消时我将people数组设置为cachedPeople
this.setState({ visible: false, people: this.state.cachedPeople });
但this.state.cachedPeople
的值在点击取消按钮之前也会成为this.state.people
的更新值,因此不会发生回复我不知道发生了什么。
到目前为止,我尝试将其保存在this.cachedPeople
而不是状态,但仍然会发生。
以下是示例代码的要点:https://gist.github.com/damathryx/4a379d3c8919ee6431ee79b7a58426c9
答案 0 :(得分:2)
负责任地克隆
你不应该克隆整个国家;如果您知道自己只更新一个对象
,那就没有意义了
const state =
[ {age: 10}, {age: 11}, {age: 12}, {age: 13}, {age: 14} ]
const nextState =
[
...state.slice (0,2),
{ ...state [2], age: 20 },
...state.slice (2)
]
console.log (state)
// [ {age: 10}, {age: 11}, {age: 12}, {age: 13}, {age: 14} ]
console.log (nextState)
// [ {age: 10}, {age: 11}, {age: 20}, {age: 13}, {age: 14} ]

您的计划可能会是什么样子(包含变量index
和age
)
onPress={() =>
this.setState ({
people: [
...this.state.people.slice (0,index),
{ ...this.state.people [index], age },
...this.state.people.slice (index)
}
})}
坚持不懈
当然,编写没有持久数据结构的函数式程序会很痛苦,这就是为什么我们有Mori或更受欢迎的Immutable之类的东西 - 这里有一个例子使用Immutable。我们使用toJS()
转换回原始Array
和Object
类型
const {List, Map} =
require ('immutable')
const state =
[ {age: 10}, {age: 11}, {age: 12}, {age: 13}, {age: 14} ]
const nextState =
List (state) .set (2,
Map (state [2]) .set ('age', 20) .toJS ()) .toJS ()
console.log (state)
// [ { age: 10 }, { age: 11 }, { age: 12 }, { age: 13 }, { age: 14 } ]
console.log (nextState)
// [ { age: 10 }, { age: 11 }, { age: 20 }, { age: 13 }, { age: 14 } ]
答案 1 :(得分:-1)
你必须克隆。人和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 });
如果适合你,请告诉我。