我想创建这样的状态:

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}`);
    });
  }


我正在映射我的数组列,所以数组中的每个项目都想将它们的状态设置为键,是否有可能?

最佳答案

有没有办法?


是的,但是您尝试的方法不正确,而不是在循环内调用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)];

关于javascript - 创建带有变量引用的 react 状态名称?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/48297639/

10-11 13:27