简体   繁体   中英

How to set redux state variable to component state

I have the below component

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

Im mapping the locArray from the redux state to the component props like below

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

export default connect(mapStateToProps)(Requirements);

so that i can initialize the state variable selectedJ based on locArray length like below

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

I feel something is wrong with this approach. I get the below error on the code that's inside the render because of this locArray that i mapped in the mapStateToProps.

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.

my code works as expected without the locArray in the mapStateToProps but i need to get that from redux store and initialize the state variable selectedJ based on this locArray.

Fairly new to redux, Any thoughts on how to achieve this would help. Thanks

I fixed this issue.

Issue was with reading rolelocArray from redux state in mapStateToProps

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

rolelocArray was not always available. It was being set on a condition in the reducer. I thought my || [] would work if rolelocArray is not available at any point in time.

But it didn't.

Instead, I was reading from another variable "rolelocRefArray" that's available available in the redux state.

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

Another way of solving this could be having initial value for rolelocArray in the redux state.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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