首页 > 解决方案 > 如何在父组件中的 fetch 调用的数据传递给它之前停止加载 React 子组件

问题描述

我正在制作一个显示应用程序及其评论的网站。每个应用程序都有一个页面,每个页面都包含应用程序的评论。如果评论是每个应用程序 API 调用中返回的数据的一部分,但评论是他们自己的对象,有自己的调用,那将是非常容易的。所以基本上我希望应用程序页面加载评论。问题是我不断收到错误,因为我的子组件由于某种原因渲染了两次,而第一次渲染时没有评论。由于某种我不明白的原因,它也在父组件之前加载。我已经通过在每一步将道具打印到控制台来确认这一点。数据呈现的顺序是:从子组件打印的道具(不包括评论,所以当我尝试提取任何数据时出现未定义的错误),从子组件打印的道具(完整的评论),然后最后打印来自异步 componentDidMount() 的数据。我正在使用异步 componentDidMount() 因为我的印象是把await this.fetchData()在 componentDidMount() 内部会导致它等到数据被获取。不是这种情况。所以,是的,如果有人能告诉我如何正确加载一次,那就太好了。我一直在尝试各种不同的东西,所以如果有些东西没有意义或加起来可能是早期的尝试,我会在编辑中澄清。

这是父母的代码

import React from 'react';
import Header from '../universal components/Header';
import DetailsAppHeader from '../details page components/DetailsAppHeader';
import FeatsComponents from '../details page components/FeatsComponents';
import SupportComponent from '../details page components/SupportComponent';
import ReviewsComponent from '../details page components/ReviewsComponent';

export default class DetailPageComponent extends React.Component {
    constructor(props){
        super(props);
        
        this.state = {
            // a bunch of stuff relating to the apps
        }

    async componentDidMount() {
        await this.fetchData()
       // this await is basically useless but it's the last thing I tried 
    }

    fetchData(){
        fetch("http://localhost:3001/reviewsForApp/" + this.state.appId)
        .then(response => response.json())
        .then(response => {
            this.setState({reviews: response.data.list})
        })
    }

    render(){
        return(
            <div>
                <div>
                    <div class="col-10 offset-1">
                        <Header />
                        <DetailsAppHeader appDetails={this.state} />
                        <FeatsComponents appDetails={this.state} />
                        <SupportComponent appDetails={this.state} />
                        <ReviewsComponent appDetails={this.state}/>
                    </div>
                </div>
            </div>
        )
    }
}

和孩子

import React from 'react';


const ReviewsComponent = (props) => (
     <div>
          {props.appDetails.reviews && <h3>Most Recent Reviews</h3>}
          {console.log(props.appDetails.reviews)}
          // first time returns undefined the second time it returns the correct data
          <p>{props.appDetails.reviews}</p>
          // this fails because the data is not loaded yet
     </div>
   )


export default ReviewsComponent;

标签: javascriptreactjscomponentsreact-component

解决方案


也许在填充状态时尝试仅渲染子组件,例如:

render(){ return(
<div>
  <div>
    <div class="col-10 offset-1">
      <Header /> {this.state && (
      <DetailsAppHeader appDetails={this.state} />
      <FeatsComponents appDetails={this.state} />
      <SupportComponent appDetails={this.state} />
      <ReviewsComponent appDetails={this.state}/> ) }
    </div>
  </div>
</div>
) }


推荐阅读