简体   繁体   English

如何在React中使用Fetch正确处理来自REST API的数据对象

[英]How to correctly handle data object from REST API using fetch in React

I have a React app that receives an object from WordPress site using fetch() over rest api (v2/posts). 我有一个React应用程序,它通过REST API(v2 / posts)上的fetch()从WordPress站点接收对象。

The object contains an "acf" entry which holds ~30 sub entries: some arrays and some are objects. 该对象包含一个“ acf”条目,其中包含约30个子条目:有些数组,有些是对象。 All generated with Advanced Custom Field plugin. 全部使用高级自定义字段插件生成。

The application is updating this data (using this.state) and the server (fetch/post) upon user request. 应用程序应用户请求更新此数据(使用this.state)和服务器(获取/发布)。 All is working. 一切正常。 I am not using express, redux and the like. 我没有使用express,redux之类的东西。

My current problem is that I cannot access the internals of the "acf" entry in render() function, while I can access it within the fetch response. 我当前的问题是我无法访问render()函数中“ acf”条目的内部,而可以在访存响应中访问它的内部。 I would like to be able to acccess 我希望能够进入

cpt['acf']['entry']['subentry']
using the entry's names. 使用条目的名称。 But I get "cannot access property of undefined..." 但是我得到“无法访问未定义的属性...”

Example: 例:

\n\n        // In constructor: //在构造函数中:\n        // this.state = { // this.state = {\n        // isLoading: false, title:"", terms:[], cpt: [] // isLoading:false,title:“”,条款:[],cpt:[]\n        // } //}\n        ... ...\n                fetch(url) 取(URL)\n                .then(response => { .then(response => {\n                    if (response.ok) 如果(response.ok)\n                        return response.json() 返回response.json()\n                    throw new Error('fetchTerm: Something went wrong ...') 抛出新错误('fetchTerm:出问题了...')\n                }) })\n                .then(cpt => { .then(cpt => {             \n                    var terms = Object.entries(cpt['acf']) var条件= Object.entries(cpt ['acf'])\n                    var title = Object.values(cpt['title']) var title = Object.values(cpt ['title'])\n\n                    this.setState({cpt, terms, title, isLoading: false}) this.setState({cpt,terms,title,isLoading:false})\n    .then( () => { .then(()=> {\n                console.log("title",this.state.cpt['title']) 的console.log( “标题”,this.state.cpt [ '标题'])\n                console.log("FAMILYLOG",this.state.cpt['acf']['familylog_array']) // shows ok console.log(“ FAMILYLOG”,this.state.cpt ['acf'] ['familylog_array'])//显示正常\n            }) })\n\n                    return (true) // void - no one is looking... return(true)//无效-没有人在寻找...\n                }) })\n        //... // ...\n        render(){ 渲染(){\n            if (this.state.isLoading) 如果(this.state.isLoading)\n                    return ( Loading ) 返回( 加载中\n        // occurs only after fetch resturn and this.state variables are instanciated //仅在获取取回并且this.state变量实例化之后才发生\n            console.log("title", this.state.title) // shows OK console.log(“ title”,this.state.title)//显示正常\n            console.log("FAIL", this.state.cpt['title']) // cannot access property of NULL/Undefined... console.log(“ FAIL”,this.state.cpt ['title'])//无法访问NULL / Undefined属性...\n            console.log("FAMILYLOG",this.state.cpt['acf']['familylog_array']) // same problem console.log(“ FAMILYLOG”,this.state.cpt ['acf'] ['familylog_array'])//同样的问题\n        } }\n\n

What am I missing? 我想念什么?

I would like to be able to acccess cpt['acf']['entry']['subentry'] 我希望能够使用cpt['acf']['entry']['subentry']

Should I regenerate the cpt into arrays/objects in the Component state? 我应该在Component状态下将cpt重新生成为数组/对象吗?

according to your code you initialize cpt: [] (which should rather be an object though) in the constructor and then you make a call to the api and only when the promise is resolved you will modify the state, the thing is it happens after the first render call is done, so you get "cannot access property of NULL/Undefined" for cpt['acf']['entry']['subentry'] , though this.state.cpt['title'] will rather return undefined in the render() 根据您的代码,您可以在构造函数中初始化cpt: [] (尽管它应该是一个对象),然后您对api进行调用,并且只有在答应被解决时,您才可以修改状态,但事情发生在第一个渲染调用已经完成,因此您会获得cpt['acf']['entry']['subentry'] this.state.cpt['title'] cpt['acf']['entry']['subentry'] “无法访问NULL / Undefined属性cpt['acf']['entry']['subentry'] ,尽管this.state.cpt['title']宁愿在render()返回undefined

Upd: To prevent this, isLoading should have been set as true in the constructor Upd:为避免这种情况,应在构造函数中将isLoading设置为true

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM