即使在使用钩子刷新ReactJS之后也获取最后一个状态
即使在刷新页面后,如何获取最后一个状态?刷新后状态返回到0即使在使用钩子刷新ReactJS之后也获取最后一个状态,reactjs,react-hooks,Reactjs,React Hooks,即使在刷新页面后,如何获取最后一个状态?刷新后状态返回到0 const [updateCounter, setUpdateCounter] = useState(0); async function updateCounter() { setUpdateCounter(updateCounter + 1); } <Button onClick={updateCounter()}>Update</Button> const[updateCounter,setUp
const [updateCounter, setUpdateCounter] = useState(0);
async function updateCounter() {
setUpdateCounter(updateCounter + 1);
}
<Button onClick={updateCounter()}>Update</Button>
const[updateCounter,setUpdateCounter]=useState(0);
异步函数updateCounter(){
setUpdateCounter(updateCounter+1);
}
更新
当updateCounter
更改时,将其放入本地存储:
const [counter, setCounter] = useState(Number(localStorage.counter) || 0);
useEffect(() => {
localStorage.counter = counter;
}, [counter]);
您也不应该同时拥有updateCounter
number(处于状态)和updateCounter
函数-使用不同的名称