【发布时间】:2017-12-05 15:30:21
【问题描述】:
所以我一直在构建一个使用 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))
这让我想到:this 在 Promise 请求中在哪里? 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 承诺中 console.logged “this”,它确实指向组件,但我不相信。由于它被隐藏在 Promise 中,我认为 this.setState 函数实际上无法设置组件的状态。
所以我在获取请求之前做了一个变量。
const that = this;
return fetch(REQUEST_URL)
.then((response) => response.json())
.then((responseJson) => {
that.setState({
isLoading: false,
data: JSON.stringify(responseJson)
})
})
现在我不是软件专家。在过去的几年里,我一直在自学这些东西,所以我的逻辑有一半时间是错误的。
所以如果我的推理是正确的还是不正确的,请告诉我!我所知道的是这对我有用;获取数据后,它会自动设置状态并重新加载,在呈现时向我显示 JSON 数据。
有什么想法吗?我完全离开这里了吗?我错过了什么吗?
【问题讨论】:
标签: javascript react-native fetch-api