React-Redux - passing down props before async data arrives

倖福魔咒の 提交于 2019-12-10 23:34:53

问题


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

回答1:


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



回答2:


You could set defaultProps:

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


来源:https://stackoverflow.com/questions/38839375/react-redux-passing-down-props-before-async-data-arrives

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!