我似乎有问题将数据推入一个状态数组。 我正试图以这种方式实现它:
this.setState({ myArray: this.state.myArray.push('new value') })
但我相信这是不正确的方式,并导致问题的可变性?
我似乎有问题将数据推入一个状态数组。 我正试图以这种方式实现它:
this.setState({ myArray: this.state.myArray.push('new value') })
但我相信这是不正确的方式,并导致问题的可变性?
当前回答
使用react钩子,你可以这样做
const [countryList, setCountries] = useState([]);
setCountries((countryList) => [
...countryList,
"India",
]);
其他回答
数组push返回长度
this.state.myArray。push('new value')返回扩展数组的长度,而不是数组本身。array .prototype.push()
我猜您希望返回值是数组。
不变性
这似乎是React的行为:
千万不要变异。直接调用setState() 替换您所做的突变。对待这个问题。就像它是那样的状态 immutable.React.Component。
我猜,你会这样做(不熟悉React):
var joined = this.state.myArray.concat('new value');
this.setState({ myArray: joined })
这条准则对我很有用:
fetch('http://localhost:8080')
.then(response => response.json())
.then(json => {
this.setState({mystate: this.state.mystate.push.apply(this.state.mystate, json)})
})
使用es6可以这样做:
this.setState({ myArray: [...this.state.myArray, 'new value'] }) //simple value
this.setState({ myArray: [...this.state.myArray, ...[1,2,3] ] }) //another array
传播的语法
用下面的方法可以检查和更新对象
this.setState(prevState => ({
Chart: this.state.Chart.length !== 0 ? [...prevState.Chart,data[data.length - 1]] : data
}));
绝不建议直接改变状态。
在以后的React版本中,推荐的方法是在修改状态时使用updater函数来防止竞争条件:
将字符串推到数组的末尾
this.setState(prevState => ({
myArray: [...prevState.myArray, "new value"]
}))
将字符串推到数组的开头
this.setState(prevState => ({
myArray: ["new value", ...prevState.myArray]
}))
将对象推到数组的末尾
this.setState(prevState => ({
myArray: [...prevState.myArray, {"name": "object"}]
}))
将对象推到数组的开头
this.setState(prevState => ({
myArray: [ {"name": "object"}, ...prevState.myArray]
}))