繁体   English   中英

可重用的组件等待数据

[英]Reusable component to wait for data

在我的许多组件中,我正在获取API数据,因此我需要等到数据加载完毕。 否则我会收到错误,因为某些方法当然不可用。

我的api查询看起来像这样

componentDidMount() {
    prismicApi(prismicEndpoint).then((api) =>
      api.form('everything')
      .ref(api.master())
      .query(Prismic.Predicates.at("my.page.uid", this.props.params.uid))
      .submit((err, res) => {
        if (res.results.length > 0) {
          this.setState({doc: res.results[0]});
        } else {
          this.setState({notFound: true});
        }
    }))
}

为此,我创建了我在所有这些文档中使用的结构:

render() {
    if (this.state.notFound) {
      return (<Error404 />);
    } else if (this.state.doc == null || !this.state.doc) {
      return (<Loading />);
    } else {
        return (
            <div className="page">
                {this.state.doc.getSliceZone('page.body').slices.map(function(slice, i){
                    return (<SliceZone slice={slice} key={i} />)
                })}
            </div>
        )
    }
}

我想把它移到一个名为Document的组件中,如下所示:

export default class Document extends React.Component {
static defaultProps = {
    doc: null,
    notFound: false
}
static propTypes = {
    doc: React.PropTypes.oneOfType([
          React.PropTypes.object,
          React.PropTypes.array
    ]),
    notFound: React.PropTypes.bool.isRequired
}
render() {
    if (this.props.notFound) {
      return (<Error404 />);
    } else if (this.props.doc == null || !this.props.doc) {
      return (<Loading />);
    } else {
        return (
            <div className="page">
                {this.props.children}
            </div>
        )
    }
}
}

然后我试着在这里使用它:

<Document doc={this.state.doc} notFound={this.state.notFound}>           
{this.state.doc.getSliceZone('page.body').slices.map(function(slice, i){
    return (<SliceZone slice={slice} key={i} />)
})}
</Document>

虽然在第二个示例中,错误消息很快显示(直到数据加载)然后消失。 我究竟做错了什么? 为什么第一个例子正常工作,第二个例子不工作?

尝试这个

<Document doc={this.state.doc} notFound={this.state.notFound}>           
{ this.state.doc && this.state.doc.getSliceZone('page.body').slices.map(function(slice, i){
    return (<SliceZone slice={slice} key={i} />)
})}
</Document>

在你的变种中,你看到一个错误,因为this.state.doc是null,直到加载数据,你看到空引用异常,看起来像。

在第一种情况下,它不计算,在第二种情况下,它首先计算,然后作为参数“children”发送到您的Document控件

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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