在Parent组件获取API数据后,同步Child组件以接受props

时间:2018-04-05 23:51:38

标签: javascript reactjs rest

我遇到了一个无法渲染子组件的问题,因为在子组件呈现之前从API检索到的数据没有发生,让我从子组件中收到错误: 未捕获的TypeError:无法读取属性' name'未定义的 由于在获取API数据之前未确定其依赖于父项的属性。

以下是特色组件(父级):

export default class Featured extends Component {

    constructor() {
        super();
        this.state = {
            restaurants :[],
        }
    }

    componentDidMount() {
        fetch('http://127.0.0.1:5000/restaurants')
        .then(results => {
            return results.json();
        }).then(data => {
            let restaurants = data.items.map((item) => {
                return (
                    {
                        name: item.name,
                        type: item.type,
                        overallRating: item.overallRating,
                        url: item.url
                    }
                )
            })
            this.setState({restaurants: restaurants});
            console.log(this.state.restaurants);
        })
    }

    render() {
        return (
            <Grid>
               <Row className="show-grid text-center">
                    <Col xs={12} sm={4} className="resto-wrapper">
                    <RestaurantCard restaurant = {this.state.restaurants[0]}/>
                    </Col>
                    <Col xs={12} sm={4} className="resto-wrapper">
                      <RestaurantCard restaurant = {this.state.restaurants[0]}/>
                    </Col>
                    <Col xs={12} sm={4} className="resto-wrapper">
                      <RestaurantCard restaurant = {this.state.restaurants[0]}/>
                    </Col>
                </Row> 
            </Grid>
        )
    }
}

这是RestaurantCard组件(孩子):

export default class RestaurantCard extends Component {
    constructor(props){
        super(props);
    }
    render() {
        return (
            <div className="restaurantCard">
                <h1>CARD</h1>
                <h1>{this.props.restaurant.name}</h1>
            </div>
        )
    }
}

我尝试了什么: ComponentWillMount,没有用。 将数据检索分离到不同的方法并在Will / Did mount生命周期方法中调用它并不起作用。

现在我被困了,因为我不确定该怎么做。状态对象从空开始,但是一旦API完成,它就会有信息,如何在API完成后运行渲染,或以更好的方式运行?

我正在考虑实现某种缓冲区或某些东西来表明api正在加载但是我不知道如何在React中做到这一点,我认为ComponentWill正在这样做,但似乎没有。任何建议将不胜感激!

谢谢。

1 个答案:

答案 0 :(得分:1)

这是你需要做的就是在获得你的道具价值之前得到api召唤的结果

你的子组件RestaurantCard中的

添加了一个if语句,用于在呈现值之前检查props的值

export default class RestaurantCard extends Component {
    constructor(props){
        super(props);
    }
    render() {
    if(!this.props.restaurant){
          return(<div>Loading .......</div>
         }
        return (
            <div className="restaurantCard">
                <h1>CARD</h1>
                <h1>{this.props.restaurant.name}</h1>
            </div>
        )
    }
}