复制状态对象,不包含某些字段

时间:2018-11-05 15:40:50

标签: javascript reactjs ecmascript-6

我需要将组件的状态传输到其父组件,但是不需要传输所有字段。

我目前正在做什么:

submitHandler = (e) => {
    e.preventDefault();
    const newState = Object.keys(this.state).map(item => {
        if(item !== 'errors')
        {
            return { item: this.state[item] }
        }
    });

    console.log(newState);
    this.props.onChange(newState);
}

显然这不是我所需要的。

state = {
    errors: {
        fio: '',
        email: '',
        phone: ''
    },
    owner: owner.Company,
    fio: null,
    company: null,
    phone: null,
    fax: null,
    email: null,
    adress: null
}

我需要转移除errors以外的所有字段。我该怎么办?

2 个答案:

答案 0 :(得分:5)

您可以使用rest运算符使其起作用:)

const { errors, ...newState } = this.state;

this.props.onChange(newState);

我在这里举例:) https://repl.it/@EQuimper/PleasantTrimDeclarations

答案 1 :(得分:1)

使用rest运算符进行对象分解提供了一种方便的方式来复制对象,同时省略特定字段。在下面的示例中,newState将是this.state的副本,减去errors属性:

submitHandler = e => {
  e.preventDefault();
  const { errors, ...newState } = this.state;
  this.props.onChange(newState);
};