【问题标题】:How to declare ReactJS default props when using Redux?使用 Redux 时如何声明 ReactJS 默认 props?
【发布时间】:2017-01-07 13:36:28
【问题描述】:

在 react 中声明默认道具的正确方法是什么,这样当我在使用 redux 异步分配的道具上调用 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);

【问题讨论】:

标签: reactjs react-redux


【解决方案1】:

以下是使用 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 有关!

问题是由您的reducer 引起的。您必须声明initial state shape,此外,您必须在每个reducer 中指定初始状态。 Redux 将首次使用undefined 状态调用我们的reducer。这是我们返回应用初始状态的机会。

设置初始状态:

const searchPropsInitialState = {
  data: []
};

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

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

  return state;
}

更多详情请见handling actions in the Redux docs

【讨论】:

  • 谢谢。我理解你所说的一切,我已经尝试了一切,但我一定错过了一些东西。我正在使用 ES6,因为我能够使用示例代码中的语法。当我运行我的应用程序并执行 console.log(this.props.searchProps.data) 时,我在第一次输入渲染时得到未定义,因此我得到了错误。如果我在我的默认道具中将它设置为 [] 为什么它应该是未定义的???这正是使用默认道具的目的,所以我没有得到错误。
  • 和redux有关系吗?我已经编辑了我的初始示例代码以包含 mapStatetoProps 和 redux 的连接代码。
  • @user1991118 啊,对,和Redux有关! :) 我刚刚编辑了我的答案,请参阅上面的编辑。也请在您的问题中添加“Redux”标签。
  • 就是这样!!!!万岁!!!!我没有意识到我没有在我的减速器中设置默认值。我还更新了问题标题和关键字以包含 redux。这解决了我的问题,但我也想确定在我的组件中分配 defaultProps 的语法。所以基本上我的 defaultProps 被忽略的原因是因为 redux 优先?这意味着如果数据来自 Redux,那么即使您在 defaultProps 中提供了默认值,如果未在 reducer 中设置默认值,也会始终导致数据最初显示为未定义??
  • 是的,没错。实际上在大多数情况下——对于你通过 Redux 操作的数据(保存你的应用程序存储的数据)——你不需要在你使用它的 ReactJS 组件中声明一个defaultProps。不过,这取决于您的特定用例。但无论如何,现在您应该能够了解默认数据流是如何发生的。理想情况下,您应该只想在一个地方设置初始数据状态。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-11
  • 2010-12-19
  • 2020-12-09
  • 2016-04-22
  • 2020-12-14
相关资源
最近更新 更多