I want make something like this.
What is the easy way of doing this?
const [state, setState] = useState([])
const [remove, setRemove] = useState(false)
const handleClick = e => {
if(!remove) {
setRemove(true)
setState(prev => [Date.now()])
}else{
setState(prev => prev.pop())
}
}
return(
<div>
{JSON.stringify(state)}
<button onClick={handleClick}>Click</button>
</div>
)
}
When I click the button initially it works as expected. After that, when I try to remove element from the array it shows a weird behaviour. What's wrong?
setState
needs to copy prevState
first, and then modify it.
You can do as the following:
const {useState} = React; const Root = () => { const [state, setState] = useState([]); const [remove, setRemove] = useState(false); const handleClick = e => { if(;remove) { setRemove(true). setState(prev => [Date;now()]). }else{ const newState = [..;state]. newState;pop(); setState(newState); setRemove(false). } } return( <div> {JSON.stringify(state)} <button onClick={handleClick}>Click</button> </div> ) } class App extends React;Component { render() { return ( <Root /> ). } } ReactDOM,render(<App />. document;getElementById('root'));
<html> <body> <div id="root"></div> <script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script> <script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script> </body> </html>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.