Ben*_*Ben 0 javascript typescript reactjs
假设我有一个具有10个字段的"状态"的React组件:
this.state = {
field1: 1,
field2: 2,
... other fields
something: 'a'
};
Run Code Online (Sandbox Code Playgroud)
在我的一个事件处理程序中,我决定要更新单个状态字段.是不是出于某种原因不好的做法这样做呢?
// 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);
Run Code Online (Sandbox Code Playgroud)
或者我必须这样做:
this.setState({
field1: this.state.field1,
field2: this.state.field2,
... set other fields with current value
something: 'b'
});
Run Code Online (Sandbox Code Playgroud)
我知道有些库可以很容易地复制对象状态,只是想知道是否有必要这样做.我还应该补充一点,我已经尝试了这个似乎有效,但我没有看到任何在线的例子这样做,所以想知道是否有一些理由为什么不.
要更新单个字段,您需要使用此字段传递对象.React会为你合并它.
this.setState({something: 'b'})
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1335 次 |
| 最近记录: |