无法访问构造函数中的 this.props 数据,react+redux

Unable to access this.props data inside constructor, react+redux

我在 Form 组件中使用 redux、redux-form 和 react-select,如下所示。我在使用 props 作为表单的 multi-select 值时遇到问题。

Multi-select 值在加载道具或刷新页面时显示并正常工作。但是,它在正常用例中似乎无法正常工作。

智能容器调用 asyncconnect 来发送簿记员数据,我在这个组件中使用 connect 来访问 this.props.bookRunners。

class Form extends Component {
  constructor(props) {
    super(props);
    const bookRunnerArray = this.getBookRunnerArray(this.props.bookRunners.bookRunners);
    this.state = {
      options: bookRunnerArray,
      value: [],
    };
  }

正在连接到商店:

const mapStateToProps = (state) => {
  return {
    bookRunners: state.bookrunners,
  };
};

const mapDispatchToProps = (dispatch) => {
  return { actions: bindActionCreators(dealActions, dispatch) }
};
export default connect(mapStateToProps, mapDispatchToProps)(Form);

当我尝试在构造函数中设置初始状态时,我认为 this.props.bookRunners 是空的。我尝试使用 componenetWillMount() 但没有运气。请帮忙!

您的 mapStateToProps 函数似乎有错字。在 return 对象上将 state.bookrunners 更改为 state.bookRunners

添加下面的代码解决了这个问题。在构造函数中访问的 super(props) 和 prop 仍然是 "fetching"。因此没有所需的数据。 componenetWillMount 也是同样的情况。但是,我能够从 componentWillReceiveProps() 访问数据。如果有人有任何想法,请告诉我。

  componentWillReceiveProps() {
    if(!this.props.bookRunners.isFetching && this.state.options.isEmpty){
      const bookRunnerArray = this.getBookRunnerArray(this.props.bookRunners.bookRunners);
      this.setState ({
        options: bookRunnerArray,
      })
    }
  }

--- 第 2 天在处理另一个有同样问题的容器。并决定 componentDidUpdate() + 在构造函数内部初始化的行为更加一致。

所以下面 + 上面显示的构造函数。

  componentDidUpdate() {
    if(!this.props.bookRunners.isFetching && this.state.options.isEmpty){
      const bookRunnerArray = this.getBookRunnerArray(this.props.bookRunners.bookRunners);
      this.setState ({
        options: bookRunnerArray,
      })
    }
  }