React JS 在状态中维护数组
React JS maintain array inside state
我一直在使用 React state 来维护一些数据。对于整数和字符串,它运行良好,但不幸的是数组不起作用。
在我的组件构造函数中,我有
constructor(props) {
super(props);
this.state = {
terms: 5,
myArray: []
}
然后,我试图在 componentDidUpdate
中维护它
componentDidUpdate() {
this.state = {
terms: this.state.terms,
myArray: this.state.myArray
}
但是 myArray: this.state.myArray
不工作。然而 terms: this.state.terms
运行良好。
有人可以帮忙吗!
您不能使用 this.state
来更新状态,您必须使用:
this.setState(newStateObject);
问题是您以错误的方式更新了 state
值,像这样更新状态值:
this.setState({
terms: this.state.terms,
myArray : this.state.myArray
});
根据DOC:
Never mutate this.state directly, as calling setState() afterwards may
replace the mutation you made. Treat this.state as if it were
immutable.
像这样更新 state array
,首先使用 slice()
创建一个副本,然后进行更改并使用 setState
更新:
let arr = this.state.myarr.slice();
arr.push('data');
this.setState({arr});
你不能像那样直接设置状态,因为它是一个数组,你必须附加值或推送值。
试试
var newArray = this.state.myArray.slice();
newArray.push("new value");
this.setState({myArray:newArray})
我在这里进行了切片以使其不可变。
我一直在使用 React state 来维护一些数据。对于整数和字符串,它运行良好,但不幸的是数组不起作用。
在我的组件构造函数中,我有
constructor(props) {
super(props);
this.state = {
terms: 5,
myArray: []
}
然后,我试图在 componentDidUpdate
中维护它componentDidUpdate() {
this.state = {
terms: this.state.terms,
myArray: this.state.myArray
}
但是 myArray: this.state.myArray
不工作。然而 terms: this.state.terms
运行良好。
有人可以帮忙吗!
您不能使用 this.state
来更新状态,您必须使用:
this.setState(newStateObject);
问题是您以错误的方式更新了 state
值,像这样更新状态值:
this.setState({
terms: this.state.terms,
myArray : this.state.myArray
});
根据DOC:
Never mutate this.state directly, as calling setState() afterwards may replace the mutation you made. Treat this.state as if it were immutable.
像这样更新 state array
,首先使用 slice()
创建一个副本,然后进行更改并使用 setState
更新:
let arr = this.state.myarr.slice();
arr.push('data');
this.setState({arr});
你不能像那样直接设置状态,因为它是一个数组,你必须附加值或推送值。
试试
var newArray = this.state.myArray.slice();
newArray.push("new value");
this.setState({myArray:newArray})
我在这里进行了切片以使其不可变。