【发布时间】:2016-05-29 17:21:12
【问题描述】:
我正在以模式渲染一个数组。一旦模态关闭,我需要清空数组。以下代码在单击 closeModal 时更新数组但不清除数组。
constructor(props,context) {
super(props,context);
this.state = {
myArray: []
};
}
pushData(newVar) {
this.setState((state) => {
myArray: state.myArray.push(newVar)
});
}
closeModal() {
this.setState({
myArray: []
})
}
【问题讨论】:
-
类似 this.state.myarray=[]
-
嘿抱歉你是对的@Antonio this.state.myarray=[] 解决了我的问题。
-
推送数据看起来很奇怪...我会写 this.state.myArray.push(newVar)
-
this.state.myArray.push(newVar) 这种推送方式对我不起作用。我也试过 .concat 但没用
-
state.myArray.push(newVar)也不会按预期运行。Array.prototype.push返回新数组的长度,而不是其中包含新值的数组。setState(state => ({myArray: state.myArray.concat(newVar)}))更接近您要查找的内容。
标签: javascript reactjs functional-programming ecmascript-6