我创建了一个这样的函数。
export function Counter() {
const [count, setCount] = useState(0);
const countUp = () => {
setCount(count + 1);
}
const countUpAndShow = () => {
setCount(count + 1);
alert(count);
}
// I won't call after countUp function, call only countUpAndShow function.
useEffect(() => {
alert(count);
},[count])
return <div>
<button onClick={countUp}>count up!</button>
<button onClick={countUpAndShow}>show count!</button>
</div>
}
我想在 alert(count)
之后调用 setCount()
。
但 alert(count)
未正确显示计数。
然后,我像上面一样使用 useEffect
。但我只想调用 alert()
countUpAndShow
函数。
怎么解决?
答案 0 :(得分:3)
有多种方法可以解决这个问题。我建议使用 React ref 来切换 show
“状态”,这样它就可以存在于 React 组件生命周期和 React 挂钩依赖项之外。我还建议在增加计数器状态值时使用功能更新,因为这将正确地从任何先前的状态与回调入队的状态进行更新。换句话说,它避免了陈旧的状态封闭。
function Counter() {
const show = useRef(false);
const [count, setCount] = useState(0);
const countUp = () => {
setCount((count) => count + 1);
};
const countUpAndShow = () => {
setCount((count) => count + 1);
show.current = true;
};
useEffect(() => {
if (show.current) {
alert(count);
show.current = false;
}
}, [count]);
return (
<div>
<button onClick={countUp}>count up!</button>
<button onClick={countUpAndShow}>show count!</button>
</div>
);
}
答案 1 :(得分:-1)
试试这个。
export function Counter() {
const [count, setCount] = useState(0);
const [show, setShow] = useState(false);
const countUp = () => {
setCount(count + 1);
}
const countUpAndShow = () => {
setCount(count + 1);
setShow(true)
alert(count);
}
// I won't call after countUp function, call only countUpAndShow function.
useEffect(() => {
if(show) {
alert(count);
setShow(false);
}
},[show])
return <div>
<button onClick={countUp}>count up!</button>
<button onClick={countUpAndShow}>show count!</button>
</div>
}