我看到一个反应组件有state
显示如下:
class MyComp extends BaseComponent {
constructor(props) {
super(props);
this.state = {
selectedColumns: [],
params: {
offset: 0,
sort_by: {}
}
}
...
}
}
然后该反应组分具有下面的方法getValue
。在此方法中,allParams
对象是使用扩展语法创建的。即它是传播方法参数params
,然后在组件状态更新params
对象。
getValue(params){
const allParams = {
...this.state.params,
...params
}
this.setState((prevState) => {
return {
...prevState,
params: allParams
}
})
...
}
然后在MyComp
中的子组件中调用它,如下所示:
goNext() {
const offset = 15 // IT IS NOT JSON, it is a value 15.
this.props.getValue({
offset
})
}
我看到setState
还可以,但allParams
创作是否正确? params
不能成为与...
一起使用的对象(json)吗?我错过了什么吗?
在其他情况下,扩展语法使用如下:
const ob1 = {foo: 123};
const ob2 = {bar: 234};
const merged = {...ob1, ...ob2};
console.log(merged) //Output: { foo: 123, bar: 234 }
但就我而言,它将是:
const ob1 = {foo: 123};
const ob2 = 15;
const merged = {...ob1, ...ob2};
console.log(merged) //Output: { foo: 123}, and ob2 is not assigned!
ES6扩展运算符可用于对象以将其值“扩展”到另一个对象中以创建该对象的克隆。它在概念上类似于使用Object.assign
样品
const x = { a : 1 };
const y = {...x}; // y = {a:1} Equivalent to : const y = Object.assign({},x);
const z = {...x , b: 2} // z = {a:1,b:2} Equivalent to Object.assign({a:1},{b:2})
const w = {...x , a: 2} // w = {a:2} Equivalent to Object.assign({a:1},{a:2})
const p = {a:2, ...x} // p={a:1} Equivalent to using Object.assign({a:2},{a:1})
Handy link explaining this in the context of Redux
编辑:基于评论中的讨论:在您的goNext
方法中,当发生这种情况时:
this.props.getValue({
offset
})
你实际上是在创建一个像{offset:15}
这样的对象。因此,当它在getValue
中使用时,如:
const allParams = {
...this.state.params,
...params
}
您基本上用15覆盖旧的偏移值并创建一个新对象。基本上,我们不是在15
上而是在{offset:15}
上