setArray(oldArray => [...oldArray,newValue] );
const {useState, useCallback} = React;
function Example() {
const [theArray, setTheArray] = useState([]);
const addEntryClick = () => {
setTheArray(oldArray => [...oldArray, `Entry ${oldArray.length}`]);
};
return [
<input type="button" onClick={addEntryClick} value="Add" />,
<div>{theArray.map(entry =>
<div>{entry}</div>
)}
</div>
];
}
ReactDOM.render(
<Example />,
document.getElementById("root")
);
this.setState(prevState => ({
arrayvar: [...prevState.arrayvar, newelement]
}))
stackoverflow:https://stackoverflow.com/questions/37435334/correct-way-to-push-into-state-array