React:你可以将setState与现有状态对象一起使用吗? [英] React: can you use setState with existing state object?

查看:147
本文介绍了React:你可以将setState与现有状态对象一起使用吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个具有10个字段的状态的React组件:

Lets say I have a React component that has a "state" with 10 fields:

this.state = {
    field1: 1,
    field2: 2,
    ... other fields
    something: 'a'
};

在我的一个事件处理程序中,我决定要更新单个状态字段。是不是出于某种原因这样做是不好的做法?

In one of my event handlers, I decide I want to update a single state field. Is it for some reason bad practice to do it like this?

// state has 10 other properties not touched here, and I want them to
// retain their existing values
this.state.something = 'b';
this.setState(this.state);

或者我必须这样做:

this.setState({
    field1: this.state.field1,
    field2: this.state.field2,
    ... set other fields with current value
    something: 'b'
});

我知道有些库可以轻松复制对象状态,只是想知道它是否是必须这样做。我还应该补充一点,我已经尝试了这个似乎有效,但我没有看到任何在线的例子这样做,所以想知道是否有一些理由为什么不。

I'm aware there are libraries that make it easy to copy object state, just wondered if it is necessary to do that. I should also add that I have tried this and it seems to work, but I haven't seen any examples online do this so wondered if there is some reason why not.

推荐答案


不要直接改变this.state,因为之后调用setState()可能会
替换你所做的突变。将this.state视为
immutable。

NEVER mutate this.state directly, as calling setState() afterwards may replace the mutation you made. Treat this.state as if it were immutable.

使用 Object.assign for clone object

use Object.assign for clone object

const newState = Object.assign({}, this.state, {
  something: 'b'
})

this.setState(newState)

或者你可以合并当前状态:

Or you can merge current state:

this.setState({
  something: 'a',
  something2: 'b', 
})

这篇关于React:你可以将setState与现有状态对象一起使用吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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