3点实际上在这里做了什么

时间:2018-04-09 09:07:50

标签: javascript reactjs ecmascript-6 spread-syntax

我看到了一个反应组件,其中显示了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!

1 个答案:

答案 0 :(得分:0)

可以在对象上使用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覆盖旧的偏移值并创建一个新对象。基本上,我们 NOT 传播15但超过{offset:15}