What is the right way to declare default props in react so that when I call map on a prop that is asynchronously assigned using redux I do not get an undefined error? Right now, with the following syntax I get an error when trying to assign trans_filter because data is undefined in the initial call to render.
class ContainerComponent extends React.Component {
static defaultProps = {
searchProps: {
data: []
}
};
constructor(props) {
super(props);
}
render(){
let trans_filter = JSON.parse(JSON.stringify(this.props.searchProps.data));
}
}
const mapStateToProps = (state) => ({
searchProps: state.searchProps
});
export default connect(mapStateToProps, {getTransactionsAll})(ContainerComponent);
Here's how you can declare default props when using the ES6 class syntax for creating ReactJS components:
Additionally, there is another syntax for declaring
defaultProps
. This is a shortcut, but it will work only if your build has ES7 property initializers turned on. I assume that's why it doesn't work for you, because I see no issues with your syntax:Edit: after you shared your
mapStateToProps
, yes, it has something to do with Redux!The issue is caused by your
reducer
. You must declare initial state shape and moreover, you must specify the initial state in each reducer. Redux will call our reducer with anundefined
state for the first time. This is our chance to return the initial state of our app.Set initial state:
Then, in your reducer when you manipulate
searchProps
do:For more details, see handling actions in the Redux docs.