[英]React Native Fetch does not render response until after clicking screen
所以我一直在构建一个使用Fetch API发出请求的应用程序。 不幸的是,我认为Facebook文档中显示的代码(可能是?)不正确。
问题
启动应用程序时,Fetch会调用URL来提取JSON数据。
componentDidMount(){
return fetch(REQUEST_URL)
.then((response) => response.json())
.then((responseJson) => {
this.setState({
isLoading: false,
data: JSON.stringify(responseJson)
})
})
.catch((error) => {
console.error(error);
});
}
这类似于Facebook文档提供的代码。
问题是,当我启动应用程序时,数据不会在渲染功能中呈现。
render() {
if (this.state.isLoading) {
return (
<View style={{flex: 1, paddingTop: 20}}>
<ActivityIndicator />
</View>
);
}
var data = this.state.data;
return this.renderData(data);
}
至少,直到我点击/触摸屏幕后才会渲染。 触摸屏幕后,数据呈现。 否则,它只会处于永久的“加载”状态。
解?
我记得在过去的某个时候,我不得不将事件处理程序绑定到各自的控件(例如,this.handleClick = this.handleClick.bind(this))
这让我想到:承诺请求中的这个在哪里? 这指向哪里?
componentDidMount(){
return fetch(REQUEST_URL)
.then((response) => response.json())
.then((responseJson) => {
this.setState({ <--- **Where are you going?**
isLoading: false,
data: JSON.stringify(responseJson)
})
})
我在responseJson的promise中记录了“this”,它确实指向了组件,但我不相信。 由于它被置于promise的内部,我认为this.setState函数实际上不能设置组件的State。
所以我在获取请求之前创建了一个变量。
const that = this;
return fetch(REQUEST_URL)
.then((response) => response.json())
.then((responseJson) => {
that.setState({
isLoading: false,
data: JSON.stringify(responseJson)
})
})
现在我不是软件大师。 在过去的几年里,我一直在教自己这些东西,所以我的逻辑关闭了一半。
所以,如果我的推理是正确的或不正确的,请告诉我! 我所知道的是,这对我有用; 获取数据后,它会自动设置状态并重新加载,在呈现时显示JSON数据。
有什么想法吗? 我完全离开了吗? 我错过了什么吗?
我看到了像你这样的问题。 这不是关于你的代码。 在Remote JS debugging
模式下使用该应用程序? 如果是这样,请将其禁用。 如果它不起作用,请尝试安装发行版。
(代表OP发布) 。
显然这是由于在调试模式下运行应用程序。 使用this.setState运行应用程序在不处于调试模式时工作正常。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.