I use the code below to set default props on a React component but it doesn\'t work. In the render()
method, I can see the output \"undefined props\" was printe
class Example extends React.Component {
render() {
return <h1>{this.props.text}</h1>;
}
}
Example.defaultProps = { text: 'yo' };
First you need to separate your class from the further extensions ex you cannot extend AddAddressComponent.defaultProps
within the class
instead move it outside.
I will also recommend you to read about the Constructor and React's lifecycle: see Component Specs and Lifecycle
Here is what you want:
import PropTypes from 'prop-types';
class AddAddressComponent extends React.Component {
render() {
let { provinceList, cityList } = this.props;
if(cityList === undefined || provinceList === undefined){
console.log('undefined props');
}
}
}
AddAddressComponent.contextTypes = {
router: PropTypes.object.isRequired
};
AddAddressComponent.defaultProps = {
cityList: [],
provinceList: [],
};
AddAddressComponent.propTypes = {
userInfo: PropTypes.object,
cityList: PropTypes.array.isRequired,
provinceList: PropTypes.array.isRequired,
}
export default AddAddressComponent;
If you're using a functional component, you can define defaults in the destructuring assignment, like so:
export default ({ children, id="menu", side="left", image={menu} }) => {
...
};