【问题标题】:React: useState hooks inside nested arrow functionsReact:嵌套箭头函数中的 useState 钩子
【发布时间】: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


【解决方案1】:

你想试试这个吗?


function F() {
 const [x, setX] = useState(0);
 const nestedSetX = () => {
  setX((prevState) => prevState + 1);
 }
 return <button onClick={() => nestedSetX() }>{x}</button>
}

【讨论】:

  • 谢谢。这行得通。能否请您补充一些详细信息为什么会这样?
猜你喜欢
  • 2020-05-07
  • 2020-06-07
  • 2023-03-19
  • 2020-11-30
  • 2021-02-07
  • 1970-01-01
  • 1970-01-01
  • 2021-04-04
  • 1970-01-01
相关资源
最近更新 更多