javascript - React Native Fetch API 不返回我的调用

标签 javascript react-native fetch-api

抱歉标题中的笑话。

我目前正在研究 React Native 中的 fetch API,但我遇到了一些我无法解决的问题。

因此,我尝试从服务器获取消息,我通过以下方式使用获取 API 调用该消息:

var serverCommunicator = {
    test: function() {
        fetch(baseUrl  , {
          method: 'GET',
          headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json',
          }
        })
        .then((response) => response.text())
        .then((responseText) => {
             return (JSON.stringify(responseText));
        })
        .catch((error) => {
          console.warn(error);
        }).done();
    },
module.exports = serverCommunicator;

当我仅使用 console.log(responseText) 进行测试时,我的日志给出了正确的消息。但是,现在当我想尝试将代码中的内容作为消息放入 View 中时,它不会按预期返回。调用方式如下:

import Method from '../Services/Methods';
.
.
.
<View style={styles.card}>
   <CardView
      message={Method.test()} 
    />

我可以看到像这样调用时如何正确调用函数测试,但由于某种原因,它没有写入消息。

最佳答案

这是一个典型的异步问题,您的 then 函数在 render 已经被调用后返回,没有地方可以返回

最常见的解决方案:显示空状态消息/加载指示器并在组件安装时获取服务器信息。当您的 promise 返回并触发 then 回调时,使用您的预期值设置将触发重新渲染的组件状态。

类扩展 React 组件

class YourComponent extends Component {
  constructor() {
    super()
    this.state.text = 'Loading, please wait!' // default text
  }

  componentDidMount() {
    fetch(baseUrl, options)
      .then((response) => response.text())
      .then((responseText) => {
         this.setState({ text: responseText }) // this triggers a re-render!
      })
  }

  render() {
    return (
      <View style={styles.card}>
        <CardView
          message={this.state.text} // <-- will change when fetch call returns
        />
      </View>
    )
  }

}

React.createClass

var YourComponent = React.createClass({
  getInitialState() {
    return { text: 'Loading, please wait!' }
  }, // <-- comma between functions, because object keys

  componentDidMount() {
    fetch(baseUrl, options)
      .then((response) => response.text())
      .then((responseText) => {
         this.setState({ text: responseText }) // this triggers a re-render!
      })
  },

  render() { /* ..same as above.. */ }
})

如果您想在服务中保留 fetch 调用所在的当前架构,您需要返回对 fetch 的初始调用,这将返回一个 promise 。然后你可以在你的构造函数中连接 then:

var serverCommunicator = {
  test: function() {
    return fetch(baseUrl, options) // return a promise! ..important!
      .then((response) => response.text())
      .then((responseText) => {
         return responseText
      })
  }
}

然后你导入的函数会返回一个 promise..

import Method from '../Services/Methods'

...

componentDidMount() {
  Method.test().then(responseText => {
    this.setState({ text: responseText })
  })
]

  ....

希望这能让你更清楚地了解 promises 是如何工作的,以及如何在 React 中使用 state 捕获异步数据!

关于javascript - React Native Fetch API 不返回我的调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37035423/

相关文章:

javascript - jquery 模态中的 document.write( )

javascript - 在 React-Native 的非异步函数中调用异步函数 - Firebase

reactjs - Redux 形式,提供给 'value' 的类型 'number' 的无效 prop 'TextInput' ,预期为 'string'

JavaScript 提取 - 无法在 'json' : body stream is locked 上执行 'Response'

javascript - 在 Javascript 中发出顺序 POST 请求的最佳方法

php 网站和 Jquery $.ajax()

javascript - if 语句显示在文本框中而不执行计算

Javascript - 如何从类中调用类中的函数?

reactjs - 如何在 React Native 中向数组添加引用?

javascript - GET 请求使用 Basic Auth 从 Postman 工作,而不是从浏览器工作