如何在 React Native 中将 Json 响应对象分配给状态对象
How to assign Json response object to state object in react native
获取响应包含(Json)许多键和相应的值我想将Json对象分配给状态对象我们如何实现?
我试过跟随但没成功
....
.then(responseobj => {
this.setState({
state_object:responseobj,
})
首先,为什么它不起作用?有什么错误吗?
无论如何,我总是创建一个新变量并将获取的 responsejson 放入其中。
试试这个:
.then(responseobj => {
let responseToHandle = responseobj;
this.setState({
state_object: responseToHandle,
})
另一个解决方案可能是在 fetch 函数中你不能访问这个对象,我总是在 class 的顶部创建一个名为 self 的变量。然后在构造函数组件方法中,我将 this 分配给 self,然后所有需要 this 的操作都可以通过 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,
})
.....
我能告诉你的就这些了,祝你好运!
If you are using fetch library to make API calls.
.then((responseobj) => responseobj.json())
.then((jsonResponse) => {
this.setState({
state_object:jsonResponse,
})
})
获取响应包含(Json)许多键和相应的值我想将Json对象分配给状态对象我们如何实现?
我试过跟随但没成功
....
.then(responseobj => {
this.setState({
state_object:responseobj,
})
首先,为什么它不起作用?有什么错误吗? 无论如何,我总是创建一个新变量并将获取的 responsejson 放入其中。 试试这个:
.then(responseobj => {
let responseToHandle = responseobj;
this.setState({
state_object: responseToHandle,
})
另一个解决方案可能是在 fetch 函数中你不能访问这个对象,我总是在 class 的顶部创建一个名为 self 的变量。然后在构造函数组件方法中,我将 this 分配给 self,然后所有需要 this 的操作都可以通过 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,
})
.....
我能告诉你的就这些了,祝你好运!
If you are using fetch library to make API calls.
.then((responseobj) => responseobj.json())
.then((jsonResponse) => {
this.setState({
state_object:jsonResponse,
})
})