React:嵌套箭头函数中的 useState 钩子
React: useState hooks inside nested arrow functions
我一直在尝试了解从嵌套箭头函数内部更新功能组件状态的正确方法是什么。在内部,据我所知,这些函数的状态是陈旧的,因此:
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>
}
你想试试这个吗?
function F() {
const [x, setX] = useState(0);
const nestedSetX = () => {
setX((prevState) => prevState + 1);
}
return <button onClick={() => nestedSetX() }>{x}</button>
}
我一直在尝试了解从嵌套箭头函数内部更新功能组件状态的正确方法是什么。在内部,据我所知,这些函数的状态是陈旧的,因此:
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>
}
你想试试这个吗?
function F() {
const [x, setX] = useState(0);
const nestedSetX = () => {
setX((prevState) => prevState + 1);
}
return <button onClick={() => nestedSetX() }>{x}</button>
}