【发布时间】:2021-03-25 14:15:55
【问题描述】:
我一直试图了解从嵌套箭头函数内部更新功能组件状态的正确方法是什么。在内部,据我所知,这些函数的状态是陈旧的:
function F() {
const [x, setX] = useState(0);
const nestedSetX = () => {
setX(x + 1);
}
return <button onClick={nestedSetX}>{x}</button>
}
我发现使用 refs 有效:
function F() {
const [x, setX] = useState(0);
const xRef = useRef(0);
const nestedSetX = () => {
xRef.current = xRef.current + 1;
setX(xRef);
}
return <button onClick={nestedSetX}>{x}</button>
}
但这似乎是一种非常尴尬的做法。 正确的做法是什么?
编辑(解决方案):
function F() {
const [x, setX] = useState(0);
const nestedSetX = () => {
setX(x => x + 1);
}
return <button onClick={nestedSetX}>{x}</button>
}
【问题讨论】:
-
这应该可以工作 setX(x => x + 1);这样就可以得到当前状态值
标签: reactjs use-state react-functional-component