首页 > 解决方案 > 来自 API 端点的数据在 React 的子组件中未定义

问题描述

祝大家有美好的一天!我有这种情况:我使用 Apollo 客户端从 React 的父类组件中的 GraphQL API 端点获取数据。我将此数据传递给子类组件。第一次一切正常,但在页面刷新后,子组件中的数据变得未定义并且应用程序崩溃。

这是情况的表示:

父组件

import React, { Component } from 'react'
import { gql } from "apollo-boost";
import {graphql} from 'react-apollo';
import ChildComponent from './ChildComponent'

const getProducts = gql`
{
    category {
        products {
            id
            name
            gallery   
           
         } 
            
     }
 }
 `

 class ParentComponent extends Component {
   constructor(props) {
        super(props)
        this.state = {
          products: []
        }
   }

   componentDidMount() {
       setTimeout(() => {
          this.setState({
            products: [...this.props.data.category.products]
        })
        
      }, 1000)
   }

    render () {
     let products = this.state.products;

      return (
         <div><ChildComponent  theProducts = {products}/></div>   
   
      )


   }

}

export default graphql(getProducts)(ParentComponent);

子组件

import React, { Component } from 'react'



 class ChildComponent extends Component {
   constructor(props) {
        super(props)
        this.state = {
          products: this.props.theProducts
        }
   }

   

    render () {
     let item = this.state.products.find(each => each.id === id);

      return (
         <div>
            <ul>
                <li>{item.name}</li>
                <li><img src= {item.gallery[0]} alt="product"></img></li>
           </ul>
        </div>   
   
      )


   }

}

export default ChildComponent;

因此,当应用程序启动时,一切似乎都运行良好。但是,如果我刷新页面,它会引发错误并说名称未定义,画廊未定义。很明显,数据没有传递到 ChildComponent。有没有办法确保数据随时进入?先感谢您。

标签: reactjsgraphql

解决方案


You use theProducts in the ChildComponent but you pass theProduct from ParentComponent . And state product also has the same error. Just update to theProducts and product


推荐阅读