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

How to declare ReactJS default props when using Redux?

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

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 class 语法创建 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有关!

问题是由您的 reducer 引起的。您必须声明 initial state shape 而且,您必须在每个 reducer 中指定初始状态。 Redux 将第一次使用 undefined 状态调用我们的 reducer。这是我们 return 应用程序初始状态的机会。

设置初始状态:

const searchPropsInitialState = {
  data: []
};

然后,在你的 reducer 中操作 searchProps 时做:

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

  return state;
}

有关详细信息,请参阅 handling actions in the Redux docs