【问题标题】:React Native Fetch API not returning my callsReact Native Fetch API 不返回我的调用
【发布时间】:2016-08-30 08:17:45
【问题描述】:

抱歉标题中的玩笑。

我目前正在探索 react native 中的 fetch API,但我遇到了一些我无法解决的问题。

所以,我正在尝试从服务器获取消息,我使用 fetch 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()} 
    />

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

【问题讨论】:

    标签: javascript react-native fetch-api


    【解决方案1】:

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

    最常见的解决方案:在组件挂载时显示空状态消息/加载指示器并获取服务器信息。当您的承诺返回并触发 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.. */ }
    })
    

    如果您想在服务中保留 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 })
      })
    ]
    
      ....
    

    希望能澄清一下 Promise 的工作原理,以及如何在 React 中使用 state 捕获异步数据!

    【讨论】:

    • 很好的解释!当我试图运行你的东西时,它说 super() 在类构造函数之外。但是,我目前正在将此视图作为 var Home = createClass({}) 运行并导出模块,这可能是个问题吗? (我阅读了一些关于两者之间差异的讨论)
    • React.createClass ?如果是这样,我可以更新我的答案以使用该样式。你有import 所以我假设你使用的是class
    • 是的,当然,我的错我错过了,当然是 React.createClass。如果你能做到,我将永远感激不尽。
    • 添加React.createClass版本
    猜你喜欢
    • 2018-11-12
    • 2021-11-04
    • 2019-08-03
    • 2018-02-28
    • 2019-07-03
    • 2018-03-01
    • 1970-01-01
    • 2022-12-02
    • 2016-11-08
    相关资源
    最近更新 更多