簡體   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