假设我有一个具有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)
我知道有些库可以很容易地复制对象状态,只是想知道是否有必要这样做.我还应该补充一点,我已经尝试了这个似乎有效,但我没有看到任何在线的例子这样做,所以想知道是否有一些理由为什么不.
在Perl中是否有任何本机方式可以知道访问哈希的密钥是什么?
像某些语言或代理对象中存在的魔术方法?