Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在react native中将Json响应对象分配给状态对象_Json_Object_React Native_Fetch Api - Fatal编程技术网

如何在react native中将Json响应对象分配给状态对象

如何在react native中将Json响应对象分配给状态对象,json,object,react-native,fetch-api,Json,Object,React Native,Fetch Api,fetch response包含(Json)许多键和相应的值,我想将Json对象分配给state对象,说明如何实现 我试过跟随,但没有成功 .... .then(responseobj => { this.setState({ state_object:responseobj, }) 首先,为什么它不起作用?有错误吗? 无论如何,我总是创建一个新变量,并将fetch的responsejson放入其中。 试试这个: .then

fetch response包含(Json)许多键和相应的值,我想将Json对象分配给state对象,说明如何实现

我试过跟随,但没有成功

....
      .then(responseobj => {
        this.setState({
          state_object:responseobj,
        })

首先,为什么它不起作用?有错误吗? 无论如何,我总是创建一个新变量,并将fetch的responsejson放入其中。 试试这个:

.then(responseobj => {
    let responseToHandle = responseobj;
    this.setState({
      state_object: responseToHandle,
    })
另一个解决方案可能是,在fetch函数中,您无法访问该对象,我总是在类的顶部创建一个名为self的变量。然后,在构造函数组件方法中,我将其分配给self,然后self对象可以访问所有需要它的操作

例如:

import React from ........
//more of your imports......

var self;
export default class YourClassOrComponent extends Component{

  ......

 constructor(){
   super();
   self = this;
   ......
 }

// using setState inside a function with self -->
....
.then(responseobj => {
let responseToHandle = responseobj;
self.setState({ // <----- Note that I use here self instead of this
  state_object:responseobj,
})
.....
import React from。。。。。。。。
//更多的进口。。。。。。
var-self;
导出默认类YourClassOrComponent扩展组件{
......
构造函数(){
超级();
self=这个;
......
}
//在具有self-->的函数中使用setState
....
.然后(responseobj=>{
让responseToHandle=responseobj;
self.setState({//
If you are using fetch library to make API calls. 

.then((responseobj) => responseobj.json())
.then((jsonResponse) => {
   this.setState({
     state_object:jsonResponse,
   }) 
})