使用Redux connect时,defaultProps是必需的吗?

问题描述 投票:0回答:3

比方说,我们有一个与Redux连接的简单React组件:

const MyComponent = ({ name }) => <p>{name}</p>

// PropTypes definition - we'll back to that in a moment...

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

export default connect(mapStateToProps)(MyComponent);

这里有一个问题 - 在将defaultProps连接到Redux商店时,是否必须为MyComponent指定MyComponent.propTypes = { name: PropTypes.string, } MyComponent.defaultProps = { name: 'hsz', } ?如下:

defaultProps

或者也许我们是安全的,没有要求指定PropTypes

reactjs redux react-proptypes
3个回答
0
投票

不,使用React的defaultPropsundefined绝不是强制性的。但是,如果支柱可能实际上不存在或者是defaultProps,那么你应该以某种方式处理这种情况。这可以通过使用render()中的解构默认值定义Watch Out for Undefined State值来完成,或者至少在尝试基于其值进行渲染之前检查该prop的值是否有意义。

有关此主题的更多建议,请参阅Dave Ceddia的帖子defaultProps


0
投票

我不认为你需要指定defaultProps。道具是通过mapStateToProps以你设置“name:state.name”的方式传递的。如果你只是拉入“状态”,那么你需要调用this.props.state.name。我想你需要调用this.props.name而不仅仅是名字。


0
投票

PropTypes绝不是强制性的。

但对于组件声明PropTypes以便读者了解此组件所需或所需的道具,这是一个很好的做法。

对于在isRequired中定义的所有道具而不是defaultProps,那么这些道具应该在qazxswpoi中定义为默认值。

© www.soinside.com 2019 - 2024. All rights reserved.