使用变量引用创建反应状态名称?

时间:2018-01-17 09:27:52

标签: javascript reactjs

我想创建这样的状态:

componentWillReceiveProps(nextProps) {
    nextProps.columns.forEach((c) => {
      const name = nextProps.columns[nextProps.columns.indexOf(c)];
      this.setState({ `${name}`: (this.props.activeHeaders.indexOf(c) > -1) });
      console.log(`${name}`);
    });
  }

我正在映射我的数组列,所以数组上的每个项目,我想将它们设置为关键字,是否有可能的方式?

2 个答案:

答案 0 :(得分:2)

componentWillReceiveProps(nextProps) {
    nextProps.columns.forEach((c) => {
      const name = nextProps.columns[nextProps.columns.indexOf(c)];
      this.setState({ [name]: (this.props.activeHeaders.indexOf(c) > -1) });
      console.log(`${name}`);
    });
  }

这应该做的工作

答案 1 :(得分:2)

  

有可能吗?

是的,但是您尝试的方式不正确,而不是在内部循环中调用setState,首先准备一个包含所有键值的对象,然后将该对象传递给setState。

像这样:

componentWillReceiveProps(nextProps) {
    let obj = {};

    nextProps.columns.forEach((c, i) => {
        const name = nextProps.columns[nextProps.columns.indexOf(c)];
        obj[name] = this.props.activeHeaders.indexOf(c) > -1;
    });

    this.setState(obj);
}

没有得到这一行的含义:

const name = nextProps.columns[nextProps.columns.indexOf(c)];
相关问题