使用Redux时如何声明ReactJS默认道具?

使用Redux时如何声明ReactJS默认道具?,reactjs,react-redux,Reactjs,React Redux,在react中声明默认道具的正确方法是什么,这样当我调用使用redux异步分配的道具上的map时,不会出现未定义的错误?现在,使用以下语法,我在尝试分配trans_filter时出错,因为在对render的初始调用中未定义数据 class ContainerComponent extends React.Component { static defaultProps = { searchProps: { data: [] } }; constructor

在react中声明默认道具的正确方法是什么,这样当我调用使用redux异步分配的道具上的map时,不会出现未定义的错误?现在,使用以下语法,我在尝试分配trans_filter时出错,因为在对render的初始调用中未定义数据

class ContainerComponent extends React.Component {
  static defaultProps = {
    searchProps: {
      data: []
    }
  };

  constructor(props) {
    super(props);
  }

  render(){
    let trans_filter = JSON.parse(JSON.stringify(this.props.searchProps.data));
  }
}

const mapStateToProps = (state) => ({
  searchProps: state.searchProps
});

export default connect(mapStateToProps, {getTransactionsAll})(ContainerComponent);

以下是使用ES6类语法创建ReactJS组件时如何声明默认道具:

class ContainerComponent extends React.Component {
  constructor(props) {
    super(props);
  }

  render(){
    let trans_filter = JSON.parse(JSON.stringify(this.props.searchProps.data));
  }
}

ContainerComponent.defaultProps = {
  searchProps: {
    data: []
  }
};

export default ContainerComponent;
此外,还有另一种用于声明
defaultProps
的语法这是一个快捷方式,但仅当您的生成启用了ES7属性初始值设定项时,它才起作用。我想这就是为什么它对您不起作用的原因,因为我认为您的语法没有问题:

class ContainerComponent extends React.Component {
  static defaultProps = {
    searchProps: {
      data: []
    }
  };

  constructor(props) {
    super(props);
  }

  render() {
    let trans_filter = JSON.parse(JSON.stringify(this.props.searchProps.data));
  }
}

export default ContainerComponent;

编辑:在您共享了
mapStateToProps
之后,是的,它与Redux有关! 该问题是由您的
减速器引起的。您必须声明,而且必须在每个减速器中指定初始状态。Redux将首次使用
未定义的
状态调用我们的reducer。这是我们返回应用程序初始状态的机会

设置初始状态:

const searchPropsInitialState = {
  data: []
};
然后,当您操作
searchProps
do时,在减速机中:

function yourReducer(state = searchPropsInitialState, action) {
  // ... switch or whatever

  return state;
}

有关更多详细信息,请参阅。

可能是您可以发布
connect
和减速器的代码吗?这些建议不太靠谱。谢谢。我明白你说的每一句话,我已经试过了,但我肯定错过了什么。我使用ES6,因为我能够使用示例代码中的语法。当我运行我的应用程序并运行console.log(this.props.searchProps.data)时,我在第一次输入render时得到了未定义的结果,因此出现了错误。如果我在默认道具中将它设置为[],为什么它应该是未定义的???这正是使用默认道具的目的,所以我不会出错。这与redux有关吗?我已经编辑了我的初始示例代码,以包含redux的MapStateTops和connect代码。@user1991118啊,是的,它与redux有关:)我刚刚编辑了我的答案,请看上面的编辑。请在你的问题中添加“Redux”标签。就是这样!!!!万岁!!!!我没有意识到我没有在减速器中设置默认值。我还更新了问题标题和关键字,以包含redux。这解决了我的问题,但我还想确定在我的组件中分配DefaultProp的语法。所以基本上我的defaultProps被忽略的原因是因为redux接受了Prevendence?这意味着,如果数据来自Redux,那么不在reducer中设置默认值将始终导致数据最初显示为未定义,即使您在defaultProps中提供了默认值??是的,这是正确的。实际上,在大多数情况下,对于通过Redux操作的数据(保存应用程序存储的数据),您不需要在使用它的ReactJS组件中声明
defaultProps
。但这取决于您的特定用例。但无论如何,现在您应该能够理解默认数据流是如何发生的。理想情况下,您应该只在一个位置设置初始数据状态。