比方说,我们有一个与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
也许我们很安全,不需要指定0xA4
?
答案 0 :(得分:0)
否,从不强制使用React的PropTypes
和defaultProps
。但是,如果有可能道具实际上不存在或为undefined
,那么您应该以某种方式处理该情况。可以通过定义defaultProps
值,使用render()
中的默认结构或至少在尝试根据其值进行渲染之前检查该道具是否存在有意义的值来实现。
有关此主题的更多建议,请参阅Dave Ceddia的帖子Watch Out for Undefined State。
答案 1 :(得分:0)
我不认为您需要指定defaultProps。道具是通过设置“名称:state.name”的方式从mapStateToProps中携带的。如果仅输入“状态”,则需要调用this.props.state.name。我认为您需要调用this.props.name而不是仅在此处命名。
答案 2 :(得分:0)
defaultProps
并不是强制性的。
但是对于组件来说,PropTypes
的声明是一种很好的做法,以使读者知道该组件所需的道具。
对于PropTypes
中定义为非 isRequired
的所有道具,
那么这些道具应该在defaultProps
中定义为默认值。