我正在模态中渲染一个数组。模态关闭后,我需要清空数组。以下代码更新数组,但在单击 closeModal 时不清除数组。
constructor(props,context) {
super(props,context);
this.state = {
myArray: []
};
}
pushData(newVar) {
this.setState((state) => {
myArray: state.myArray.push(newVar)
});
}
closeModal() {
this.setState({
myArray: []
})
}
最佳答案
我发现问题是我的 closeModal 在关闭模式时根本没有被调用。我这样做是为了在 componentWillUnmount 函数上关闭 closeModal。 我知道下面的代码会导致问题。
this.state.myArray=[] // class component
const[myArray, setMyArray]=useState([]) // functional component
我改回了
this.setState({myArray: []}); // class component
setMyArray([]); // functional component
关于javascript - 如何在 React 0.14 ES6 中单击时清除状态或清空数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35466287/