何时使用 useState() 钩子的功能更新形式,例如.setX(x=>x+1) [英] When to use functional update form of useState() hook, eg. setX(x=>x+1)

查看:37
本文介绍了何时使用 useState() 钩子的功能更新形式,例如.setX(x=>x+1)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通常,当我们需要更新功能组件中的状态时,我们会这样做:

function Example() {const [count, setCount] = React.useState(0);return (<div><p>您点击了 {count} 次</p><button onClick={() =>setCount(count + 1)}>点击我

);}

我们何时以及为何需要使用功能更新表单?

function Example() {const [count, setCount] = React.useState(0);return (<div><p>您点击了 {count} 次</p><button onClick={() =>setCount(c=>c + 1)}>点击我

);}

解决方案

当 setter 可能关闭旧状态值时使用函数形式.

例如,如果发起了一个异步请求,并且您想在该请求完成后更新状态,则发出的请求的状态范围将与请求开始时的状态范围相同,这可能会有所不同作为最新的渲染状态.

如果相同的状态值刚刚更新,您可能还需要使用函数形式,例如

setValue(value + 1);//复杂的逻辑在这里如果(某些条件){setValue(value => value + 1);}

因为 setValue 的第二次调用关闭了旧的 value.

Normally when we need to update a state in a functional component, we do something like this:

function Example() {
    const [count, setCount] = React.useState(0);
    return (<div><p>You clicked {count} times</p>
                 <button onClick={() => setCount(count + 1)}>
                    Click me
                 </button>
            </div>);
}

When and why will we ever need to use the functional update form?

function Example() {
    const [count, setCount] = React.useState(0);
    return (<div><p>You clicked {count} times</p>
                 <button onClick={() => setCount(c=>c + 1)}>
                    Click me
                 </button>
            </div>);
}

解决方案

Use the function form when the setter may close over an old state value.

For example, if an async request is initiated, and you want to update state after that's done, the request that was made will have scope of the state as it was at the beginning of the request, which may not be the same as the most up-to-date render state.

You may also need to use the function form if the same state value was just updated, eg

setValue(value + 1);
// complicated logic here
if (someCondition) {
  setValue(value => value + 1);
}

because the second call of setValue closes over an old value.

这篇关于何时使用 useState() 钩子的功能更新形式,例如.setX(x=>x+1)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
前端开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆