我使用下面的代码在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.is@R_502_103@ } AddAddressComponent.defaultProps = { cityList: [],provinceList: [],} AddAddressComponent.propTypes = { userInfo: React.PropTypes.object,cityList: PropTypes.array.is@R_502_103@,provinceList: PropTypes.array.is@R_502_103@,}
你忘了关闭Class括号.
原文链接:https://www.f2er.com/react/301253.htmlclass 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.is@R_502_103@ }; AddAddressComponent.defaultProps = { cityList: [],}; AddAddressComponent.propTypes = { userInfo: React.PropTypes.object,cityList: React.PropTypes.array.is@R_502_103@,provinceList: React.PropTypes.array.is@R_502_103@,} 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" />