如何将redux状态变量设置为组件状态

plupiseo  于 2022-11-12  发布在  其他
关注(0)|答案(1)|浏览(165)

我有以下组件

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状态Map到组件属性,如下所示

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

export default connect(mapStateToProps)(Requirements);

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

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

我觉得这种方法有问题。我在渲染器内部的代码上得到了下面的错误,因为我在mapStateToProps中Map了这个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,并基于此locArray初始化状态变量selectedJ。
对redux来说相当新,任何关于如何实现这一点的想法都会有所帮助。谢谢

mctunoxg

mctunoxg1#

我已修复此问题。
从mapStateToProps中的redux状态阅读rolelocArray时出现问题

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

rolelocArray并不总是可用的。它在减速器中被设置为一个条件。我认为我的||如果rolelocArray在任何时间点都不可用,则[]将起作用。
但事实并非如此。
相反,我是从另一个变量“rolelocRefArray”中阅读的,该变量在redux状态下可用。

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

解决此问题的另一种方法是使rolelocArray的初始值处于redux状态。

相关问题