在 React 功能组件中使用 setState 的功能语法是什么? [英] What is the use of functional syntax of setState in react functional components?

查看:39
本文介绍了在 React 功能组件中使用 setState 的功能语法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们谈论的是具有 useState

说说

const [age, setAge] = useState(0)

现在让我们说在更新 age 我必须使用以前的 age

now let us say while updating age I have to use the previous age

React 文档提到了一个叫做 FUNCTIONAL UPDATES 的东西,你可以在其中传递一个函数和它的参数将是状态的先前值,例如.

React docs mention something called FUNCTIONAL UPDATES where you can pass a function and the argument to that will be the previous value of the state, eg.

setState((previousAge) => previousAge + 1)

我可以做的时候为什么要这样做

why do I need to do this when I can just do

setState(previousAge + 1)

使用函数式setState有什么好处,

what are the benefits of using functional setState,

我知道在基于类的组件中,有一种叫做状态更新批处理的功能方式,但我在功能组件文档中找不到类似的内容.

I know in class-based components there was something called batching of state updates in the functional way, but I can't find anything like that in functional components documentation.

推荐答案

它们并不相同,如果您的更新依赖于在状态中找到的先前值,那么您应该使用函数形式.如果您在这种情况下不使用函数形式,那么您的代码有时会崩溃.

They are not the same, if your update depends on a previous value found in the state, then you should use the functional form. If you don't use the functional form in this case then your code will break sometime.

为什么会坏,什么时候坏

React 功能组件只是闭包,您在闭包中拥有的状态值可能已过时 - 这意味着闭包内的值与该组件处于 React 状态的值不匹配,这可能发生在以下情况:

React functional components are just closures, the state value that you have in the closure might be outdated - what does this mean is that the value inside the closure does not match the value that is in React state for that component, this could happen in the following cases:

1- 异步操作(本例中点击慢速添加,然后多次点击添加按钮,稍后您将看到状态已重置为单击慢速添加按钮时闭包内的状态)

1- async operations (In this example click slow add, and then click multiple times on the add button, you will later see that the state was reseted to what was inside the closure when the slow add button was clicked)

const App = () => {
  const [counter, setCounter] = useState(0);

  return (
    <>
      <p>counter {counter} </p>
      <button
        onClick={() => {
          setCounter(counter + 1);
        }}
      >
        immediately add
      </button>
      <button
        onClick={() => {
          setTimeout(() => setCounter(counter + 1), 1000);
        }}
      >
        Add
      </button>
    </>
  );
};

2- 当你在同一个闭包中多次调用更新函数时

2- When you call the update function multiple times in the same closure

const App = () => {
  const [counter, setCounter] = useState(0);

  return (
    <>
      <p>counter {counter} </p>
      <button
        onClick={() => {
          setCounter(counter + 1);
          setCounter(counter + 1);
        }}
      >
        Add twice
      </button>
   
    </>
  );
}

这篇关于在 React 功能组件中使用 setState 的功能语法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆