React Native - 从JSON响应解析错误

React Native - 从JSON响应解析错误

问题描述:

这是我的代码。React Native - 从JSON响应解析错误

我在调用下面的函数来获取状态列表。

callGetStatesApi() 
{ 
    callGetApi(GLOBAL.BASE_URL + GLOBAL.Get_States) 
    .then((response) => { 
      // Continue your code here... 
      stateArray = result.data 
      Alert.alert('Alert!', stateArray) 
    }); 
} 

这里是常见的callGetApi函数,用于从GET Api获取响应。

export function callGetApi(urlStr, params) { 
    return fetch(urlStr, { 
      method: "GET", 
      headers: { 
       'Accept': 'application/json', 
       'Content-Type': 'application/json', 
      }, 
      body: JSON.stringify(params) 
     }) 
     .then((response) => response.json()) 
     .then((responseData) => { 
      result = responseData 
     }) 
     .catch((error) => { 
      console.error(error); 
      Alert.alert('Alert Title failure' + JSON.stringify(error)) 
     }); 
} 

我收到以下错误。

enter image description here

警报只显示字符串,但你的情况 “stateArray” 是复杂的对象(数组,结构..)

所以使用stateArray.toString()或JSON.stringify(stateArray ),

或者

试试下面的方法,让我知道,

fetch(GLOBAL.BASE_URL + GLOBAL.Get_States, { 
    method: 'get', 
    headers: { 'Accept': 'application/json','Content-Type': 'application/json',} 
}).then((response) => response.json()) 
.then((responseData) => { 
    console.log(responseData) // this is the response from the server 
    // Continue your code here... 
     stateArray = result.data 
     Alert.alert('Alert!', stateArray) 
}).catch((error) => { 
    console.log('Error'); 
}); 
+1

谢谢,我正在寻找以下。 “使用stateArray.toString()或JSON.stringify(stateArray)”。 –