-->

How to declare ReactJS default props when using Re

2020-07-25 10:23发布

问题:

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);

回答1:

Here's how you can declare default props when using the ES6 class syntax for creating ReactJS components:

class ContainerComponent extends React.Component {
  constructor(props) {
    super(props);
  }

  render(){
    let trans_filter = JSON.parse(JSON.stringify(this.props.searchProps.data));
  }
}

ContainerComponent.defaultProps = {
  searchProps: {
    data: []
  }
};

export default ContainerComponent;

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:

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));
  }
}

export default ContainerComponent;

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 an undefined state for the first time. This is our chance to return the initial state of our app.

Set initial state:

const searchPropsInitialState = {
  data: []
};

Then, in your reducer when you manipulate searchProps do:

function yourReducer(state = searchPropsInitialState, action) {
  // ... switch or whatever

  return state;
}

For more details, see handling actions in the Redux docs.