React Native Fetch API 没有回复我的电话

React Native Fetch API not returning my calls

抱歉标题中的笑话。

我目前正在研究 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) 进行测试时,我的日志给了我正确的消息。但是,现在当我想尝试将代码中的内容作为消息放入视图中时,它并没有像预期的那样 return 。调用方式如下:

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

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

这是一个典型的异步问题,您的 then 函数在 render 之后 return 秒已经被调用,return 无处可去。

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

class extends React Component

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.. */ }
})

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

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

然后你导入的函数将return一个承诺..

import Method from '../Services/Methods'

...

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

  ....

希望这能让您对 promise 的工作原理以及如何在 React 中使用 state 捕获异步数据有所了解!