繁体   English   中英

如何将 redux state 变量设置为组件 state

[英]How to set redux state variable to component state

我有以下组件

export class Requirements extends React.Component {
  static propTypes = {
    locArray: PropTypes.array
  };

  constructor(props) {
    super(props);
    this.state = {
      selectedJ: props.locArray.length !== 0 ? '1' : '2'
    };
    this.updateSelected = this.updateSelected.bind(this);
  }

  updateSelected(e, selectedJ) {
    this.setState({ selectedJ }, () => {
      console.log('this.state.selectedJ:', this.state.selectedJ);
    });
  }

  render() {

    return (
     // CODE
              <Field
                onChange={this.updateSelected}
              />
            <DocTable
              selectedJ={this.state.selectedJ}
            />
    );
  }
}

我将 locArray 从 redux state 映射到组件道具,如下所示

const mapStateToProps = (state, props) => ({
  locArray:
    state.role.roleArray?.[props.index].roleData?.rolelocArray || []
});

export default connect(mapStateToProps)(Requirements);

这样我就可以根据 locArray 长度初始化 state 变量 selectedJ,如下所示

constructor(props) {
    super(props);
    this.state = {
      selectedJ: props.locArray.length !== 0 ? '1' : '2'
    };
    this.updateSelected = this.updateSelected.bind(this);
  }

我觉得这种方法有问题。 由于我在 mapStateToProps 中映射的这个 locArray,我在渲染内部的代码上收到以下错误。

Error: Maximum update depth exceeded. This can happen when a component repeatedly calls setState inside componentWillUpdate or componentDidUpdate. React limits the number of nested updates to prevent infinite loops.

我的代码在没有 mapStateToProps 中的 locArray 的情况下按预期工作,但我需要从 redux 存储中获取它,并基于此 locArray 初始化 state 变量 selectedJ。

redux 相当新,任何关于如何实现这一点的想法都会有所帮助。 谢谢

我解决了这个问题。

问题是从 mapStateToProps 中的 redux state 读取 rolelocArray

const mapStateToProps = (state, props) => ({
  locArray:
    state.role.roleArray?.[props.index].roleData?.rolelocArray || []
});

rolelocArray 并不总是可用。 它被设置在减速器的条件下。 我以为我的|| 如果 rolelocArray 在任何时间点都不可用, [] 将起作用。

但它没有。

相反,我从 redux state 中可用的另一个变量“rolelocRefArray”中读取。

const mapStateToProps = (state, props) => ({
  locArray:
    state.role.roleArray?.[props.index].roleData?.rolelocRefArray || []
});

解决此问题的另一种方法可能是在 redux state 中为 rolelocArray 设置初始值。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM