简体   繁体   中英

React-Redux - passing down props before async data arrives

I receive the "Uncaught TypeError: Cannot read property 'data' of null" error in the console when I'm loading up my page. In the constructor I call an external api for data with axios using redux-promise, then I pass props down to a stateless component (TranslationDetailBox). The data arrives, and the child component will receive the props shortly (page looks ok), but first the error message appears.

this.props.translation is empty before the api call, and rendering happens before the state is updated with the external data. I believe this is the issue, but I have no clue on how to solve it.

class TranslationDetail extends Component {
  constructor(props){
    super(props);

    this.props.fetchTrans(this.props.params.id);
      }

  render() {
    return (
      <div className="container">
        <TranslationDetailBox text={this.props.translation.data.tech}/>
        <TranslationDetailBox text={this.props.translation.data.en}/>
      </div>
    );
  }
}

function mapState(state) {
  const { translation } = state;

  return { translation };
}
...

I find this to be a good use case for conditional rendering.

Your render could check to see whether the data has loaded or not and if not, render something indicating it is still loading.

A simple implementation could be:

render() {
    return (
        !this.props.data ?
            <div>Loading...</div>
        :
            <div>{this.props.data}</div>
    )   
}

You could set defaultProps :

TranslationDetail.defaultProps = {
    translation: { 
        data: {}
    }
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM