reactjs - 来自 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。有没有办法确保数据随时进入?先感谢您。
解决方案
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
推荐阅读
- javascript - 错误类型错误:无法读取 Object.eval 处未定义的属性“0”| 角 10
- ios - 是否可以加载 ios 应用程序的调试版本来测试飞行?
- python - Python:有没有办法只打印字符串中的指定字符,而让其他字符为空?
- npm - 权限被拒绝@ apply2files - /usr/local/lib/node_modules/node-red/node_modules/websocket-stream/node_modules/ws/lib/.DS_Store
- graphql-java - 如何将 JSONObject 值分配给 graphql 模式文件中的字段?
- python - 在 C 程序中调用 Python 函数
- android - 为什么我收到此错误:androidx.constraintlayout.widget.ConstraintLayout 无法转换为 android.widget.TextView?
- azure - DefaultAzureCredentials 无法在 MangedIdentity AKS 中获取凭据
- c++ - 为什么我的编译器无法识别#include
(c++)? - c - 如何使用 net-snmp 库读取 snmp 表?