React Native Fetch API不返回我的调用 [英] React Native Fetch API not returning my calls

查看:249
本文介绍了React Native Fetch API不返回我的调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对不起标题中的笑话。

我目前正在探索反应原生的fetch API,但我遇到了一些我无法包装的问题到处走走。

I am currently exploring the fetch API in react native, but I have bumped in to some issues which I cannot wrap my head around.

所以,我试图从服务器收到一条消息,我用以下方式用fetch API调用:

So, I am trying to get a message from a server, which I am calling with the fetch API in the following manner:

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中时,它不会按预期返回。以下列方式调用它:

When I tested using only console.log(responseText) my log gave me the correct message. However, now when I wanna try to put the content in the code as a message in a View it does not return as expected. Calling it in the following manner:

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

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

I can see how the function test is called properly when calling it like this, but for some reason, it does not write the message.

推荐答案

这是一个经典的异步问题,你的然后函数在 render 被调用之后返回,无处可以返回到。

This is a classic async issue, where your then function returns after render has already been called, with nowhere to return to.

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

Most common solution: display empty state message / loading indicator and fetch your server info when your component mounts. When your promise returns and then callback is fired, set the component state which will trigger a re-render, with your expected value.

类扩展React组件

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

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,这将返回一个promise。然后你可以在你的构造函数中连接然后

If you want to keep your current architecture where the fetch call is in the service, you need to return the initial call to fetch, which will return a promise. Then you can hook up then in your constructor:

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

然后导入的函数将返回一个承诺..

Then your imported function will return a promise..

import Method from '../Services/Methods'

...

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

  ....

希望能够清楚地说明承诺如何运作,以及如何在React中使用 state 捕获异步数据!

Hope that clears things up a bit about how promises work, and how to capture async data using state in React!

这篇关于React Native Fetch API不返回我的调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆