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

时间:2016-12-20 23:37:18

标签: reactjs redux react-redux redux-form

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

多重选择值显示并在加载道具或刷新页面时正常工作。但是,在正常使用情况下,它似乎无法正常工作。

智能容器调用asyncconnect来调度book-runner数据,我在此组件中使用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为空。我尝试使用componentsnetWillMount()但没有运气。请帮忙!

2 个答案:

答案 0 :(得分:0)

看起来您的mapStateToProps功能上只有拼写错误。在返回对象上将state.bookrunners更改为state.bookRunners

答案 1 :(得分:0)

添加以下代码解决了问题。在构造函数中访问的super(props)和prop都仍在“获取”。因此没有所需的数据。 componentsnetWillMount也是一样的情况。但是,我能够从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,
      })
    }
  }