在单击屏幕之前,React Native Fetch 不会呈现响应

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); 
}

至少,在 我 click/touch 屏幕之前,它不会呈现。一旦我触摸屏幕,数据就会呈现。否则,它只会一直处于 "loading" 状态。

解决方案?

我记得在过去的某个时候,我不得不将事件处理程序绑定到它们各自的控件(例如this.handleClick = this.handleClick.bind(this)

这让我开始思考:承诺请求中的 this 在哪里? this指向哪里?

componentDidMount(){
 return fetch(REQUEST_URL)
  .then((response) => response.json())
  .then((responseJson) => {
    this.setState({ <--- **Where are you going?**
      isLoading: false,
      data: JSON.stringify(responseJson)
    })
  })

我 console.logged "this" 在 responseJson 承诺中,它确实指向组件,但我不相信。由于它被埋在承诺中,我认为 this.setState 函数实际上无法设置组件的状态。

所以我在获取请求之前做了一个变量。

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 的应用程序在不处于调试模式时工作正常。