我可以改变传递给 setState 函数的状态吗? [英] Can I mutate state passed to setState function?

查看:43
本文介绍了我可以改变传递给 setState 函数的状态吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道我不应该直接在 React 中改变状态,但是当我使用函数时的情况如何:

I know I should not mutate state directly in React, but how about situation when I use function:

onSocialClick = e => {
    const id = e.target.value;
    this.setState((prevState, props) => {
        prevState[id] = !(prevState[id]);
        return prevState;
    });
};

修改传递的对象是错误的吗?

事实证明,我们大多数人都错了.React 文档现在明确说明:

It turns out that most of us were wrong here. React docs state it clearly now:

state 是对应用更改时组件状态的引用.它不应该被直接变异.相反,应该通过基于 state 和 props 的输入构建一个新对象来表示更改

state is a reference to the component state at the time the change is being applied. It should not be directly mutated. Instead, changes should be represented by building a new object based on the input from state and props

感谢@Tomáš Hübelbauer 在评论中指出.

Thanks to @Tomáš Hübelbauer for pointing it out in the comment.

推荐答案

更简洁的方法是直接引用您要编辑的属性:

A cleaner way would be to refer directly to the property you want do edit:

doIt = () => this.setState(({ [id]: prevValue }) => ({
  [id]: !prevValue,
}));

这篇关于我可以改变传递给 setState 函数的状态吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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