React-Redux - 在异步数据到达之前传递道具

bal*_*000 2 javascript reactjs redux axios

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

在api调用之前this.props.translation为空,并且在使用外部数据更新状态之前进行渲染.我相信这是问题,但我不知道如何解决它.

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 };
}
...
Run Code Online (Sandbox Code Playgroud)

Joh*_*ohn 6

我发现这是条件渲染的一个很好的用例.

您的渲染可以检查数据是否已加载,如果没有,则渲染一些表明它仍在加载的内容.

一个简单的实现可能是:

render() {
    return (
        !this.props.data ?
            <div>Loading...</div>
        :
            <div>{this.props.data}</div>
    )   
}
Run Code Online (Sandbox Code Playgroud)