我使用下面的代码在React组件上设置默认道具,但它不起作用.在render()方法中,我可以看到输出“undefined props”已经打印在浏览器控制台上.如何为组件道具定义默认值?
export default class AddAddressComponent extends Component { render() { let {provinceList,cityList} = this.props if(cityList === undefined || provinceList === undefined){ console.log('undefined props') } ... } AddAddressComponent.contextTypes = { router: React.PropTypes.object.isrequired } AddAddressComponent.defaultProps = { cityList: [],provinceList: [],} AddAddressComponent.propTypes = { userInfo: React.PropTypes.object,cityList: PropTypes.array.isrequired,provinceList: PropTypes.array.isrequired,}
你忘了关闭Class括号.
class AddAddressComponent extends React.Component { render() { let {provinceList,cityList} = this.props if(cityList === undefined || provinceList === undefined){ console.log('undefined props') } else { console.log('defined props') } return ( <div>rendered</div> ) } } AddAddressComponent.contextTypes = { router: React.PropTypes.object.isrequired }; AddAddressComponent.defaultProps = { cityList: [],}; AddAddressComponent.propTypes = { userInfo: React.PropTypes.object,cityList: React.PropTypes.array.isrequired,provinceList: React.PropTypes.array.isrequired,} ReactDOM.render( <AddAddressComponent />,document.getElementById('app') )
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script> <div id="app" />