How do I clear states or empty array on click in react 0.14 ES6?
2021-6-21 anglehua
I am rendering an array in a modal. Once the modal closes I need to empty the array.The following code updates the array but not clear array on click of closeModal.
constructor(props,context) {
super(props,context);
this.state = {
myArray: []
};
}
pushData(newVar) {
this.setState((state) => {
myArray: state.myArray.push(newVar)
});
}
closeModal() {
this.setState({
myArray: []
})
}
I found the problem is my closeModal didn’t get called at all on closing modal. I am doing that to closeModal on componentWillUnmount function.
I understood that the below code causes problem.
this.state.myArray=[] // class component
const[myArray, setMyArray]=useState([]) // functional component
I changed it back to
this.setState({myArray: []}); // class component
setMyArray([]); // functional component
You can as well use this to clear array without using setState:
this.state.your_array.length = 0;
This will work in any function.
Update
Functional component:
setYourArray([])
采集自互联网,如有侵权请联系本人