英文:
Can I use setxxx function to get current state
问题
我想在等待一些异步任务后,在回调中获取当前状态。
我认为这只会执行setStateAction函数,不会触发组件渲染或其他任何副作用。
这会导致意外问题吗?或者有更好的方法吗?
const Comp = () => {
const [state, setState] = useState(1);
const update = useCallback(async () => {
let currState;
await something; // 在等待此任务时,状态可能会更改
// 获取当前状态
setState((prev) => {
currState = prev;
return prev;
});
console.log(currState)
}, [])
return (
<>
<div>{state}</div>
<button onClick={update}>更新</button>
</>
);
};
英文:
I want to get current state in a callback after await some async task.
I think this will only execute the setStateAction function and will not trigger component rendering or any other side effects.
Will this lead to unexpected issues? Or any better way to do it?
const Comp = () => {
const [state, setState] = useState(1);
const update = useCallback(async () => {
let currState;
await something; // state may change while waiting for this task
// get current state
setState((prev) => {
currState = prev;
return prev;
});
console.log(currState)
}, [])
return (
<>
<div>{state}</div>
<button onClick={update}>update</button>
</>
);
};
答案1
得分: 0
以下是代码部分的中文翻译:
你可以使用 useRef()
定义一个引用(ref),然后在更新状态之前将状态的值放入引用中。useRef
的更改是瞬时的,它不会触发组件重新渲染。
const Comp = () => {
const [state, setState] = useState(1);
const stateBeforeUpdate = useRef();
const update = useCallback(async () => {
stateBeforeUpdate.current = state;
await something; // 在等待任务完成时,状态可能会发生变化
// 获取当前状态,你可以在这里更改状态,而 stateBeforeUpdate 仍然会保留先前的状态,即使在重新渲染后也是如此。
setState((prev) => {
return prev;
});
console.log(stateBeforeUpdate.current);
}, []);
return (
<>
<div>{state}</div>
<button onClick={update}>更新</button>
</>
);
};
请注意,这是你提供的代码的中文翻译部分,不包括问题或其他内容。
英文:
you can define a ref using useRef()
and put value of state in ref before updating state. useRef
changes are instant and it will not trigger component re-render.
const Comp = () => {
const [state, setState] = useState(1);
const stateBeforeUpdate = useRef();
const update = useCallback(async () => {
stateBeforeUpdate.current = state;
await something; // state may change while waiting for this task
// get current state, you can change state here and stateBeforeUpdate will still hold previous state even after re-render.
setState((prev) => {
return prev;
});
console.log(stateBeforeUpdate.current)
}, [])
return (
<>
<div>{state}</div>
<button onClick={update}>update</button>
</>
);
};
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论