React-Redux-在异步数据到达之前传递道具 [英] React-Redux - passing down props before async data arrives

查看:48
本文介绍了React-Redux-在异步数据到达之前传递道具的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

加载页面时,在控制台中收到未捕获的TypeError:无法读取null的属性'data'"错误.在构造函数中,我使用redux-promise用axios调用数据的外部api,然后将props传递给无状态组件(TranslationDetailBox).数据到达,子组件很快就会收到道具(页面看起来不错),但首先会出现错误消息.

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在api调用之前为空,并且渲染发生在使用外部数据更新状态之前.我相信这是问题所在,但我不知道如何解决.

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

这篇关于React-Redux-在异步数据到达之前传递道具的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆