如何在 React 中使用 fetch 正确处理来自 REST API 的数据对象
Posted
技术标签:
【中文标题】如何在 React 中使用 fetch 正确处理来自 REST API 的数据对象【英文标题】:How to correctly handle data object from REST API using fetch in React 【发布时间】:2019-04-28 17:19:05 【问题描述】:我有一个 React 应用程序,它使用 fetch() 而不是 rest api (v2/posts) 从 WordPress 站点接收对象。
该对象包含一个“acf”条目,其中包含约 30 个子条目:一些数组和一些是对象。全部使用高级自定义字段插件生成。
应用程序正在根据用户请求更新此数据(使用 this.state)和服务器(获取/发布)。一切正常。我没有使用 express、redux 等。
我当前的问题是我无法访问 render() 函数中“acf”条目的内部,而我可以在 fetch 响应中访问它。 我希望能够访问
cpt['acf']['entry']['subentry']使用条目的名称。但我得到“无法访问未定义的属性......”
例子:
// 在构造函数中: // this.state = // isLoading: false, title:"", terms:[], cpt: [] // ... 获取(网址) .then(响应 => 如果(response.ok) 返回响应.json() throw new Error('fetchTerm: 出了点问题...') ) .then(cpt => var 条款 = Object.entries(cpt['acf']) var title = Object.values(cpt['title']) this.setState(cpt, terms, title, isLoading: false) .then( () => console.log("title",this.state.cpt['title']) console.log("FAMILYLOG",this.state.cpt['acf']['familylog_array']) // 显示正常 ) return (true) // void - 没有人在看... ) //... 使成为() 如果(this.state.isLoading) 返回(加载中) // 仅在 fetch 返回并且 this.state 变量被实例化后发生 console.log("title", this.state.title) // 显示 OK console.log("FAIL", this.state.cpt['title']) // 无法访问 NULL/Undefined 的属性... console.log("FAMILYLOG",this.state.cpt['acf']['familylog_array']) // 同样的问题我错过了什么?
我希望能够访问cpt['acf']['entry']['subentry']
我应该将cpt重新生成为组件状态下的数组/对象吗?
【问题讨论】:
您能否更新您的帖子以在您将其置于状态后包含 cpt 变量的 console.log? 刚刚在 fetch() 调用和渲染中添加了 console.log()。 【参考方案1】:根据您初始化的代码
cpt: []
(它应该是一个对象)在构造函数中,然后你调用 api 并且只有当承诺被解决时你才会修改状态,事情是它发生在 第一次渲染之后 调用已完成,因此您会得到 cpt['acf']['entry']['subentry']
的“无法访问 NULL/未定义的属性”,尽管 this.state.cpt['title']
宁愿在 render()
中返回 undefined
更新:为了防止这种情况,应该在构造函数中将 isLoading 设置为 true
【讨论】:
请注意在 fetch() 完成之前阻止访问 this.state 的 isLoading 标志。至于cpt的定义。我确实尝试将它设置为一个对象并得到相同的结果 您可能希望在首次分配时将 isLoading 设置为 true 你是对的!谢谢。我在 componentDidMount 中将其设置为 true。刚刚在构造函数中意识到它更好。谢谢 太好了,很高兴为您提供帮助!以上是关于如何在 React 中使用 fetch 正确处理来自 REST API 的数据对象的主要内容,如果未能解决你的问题,请参考以下文章