我想做这样的事情。
简单的方法是什么?
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>
)
}
当我最初单击按钮时,它会按预期工作。在那之后,当我尝试从数组中删除元素时,它显示了一个奇怪的行为。怎么了?
答案 0 :(得分:0)
**import { saveAs } from 'file-saver';
const blob = new Blob([ <Invoice data={data} customer={customer}
shipped={shipped} business={business} /> ], { type: 'application/pdf'
})
saveAs(blob, "trial.pdf" );**
首先需要复制setState
,然后再进行修改。
您可以执行以下操作:
prevState
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'));