【问题标题】:react-native fetch data from REST Api failsreact-native 从 REST Api 获取数据失败
【发布时间】:2017-09-05 13:40:48
【问题描述】:

我想使用 REST API 从不同的服务器获取数据。

我这样做:

    return fetch('http://localhost:9000/processes')
        .then((response) => response.json())
        .then((responseJson) => {
            return responseJson;
        })
        .catch((error) => {
            console.error(error);
        });

在渲染函数中我有这个:

       {JSON.stringify(getProcesses().Prozess1) }

还有这个

        {JSON.stringify(getProcesses()) }

这两个例子中没有一个返回什么

其余的 API 应该返回这个:

{
  "Prozess1": "Hallo ich bin ein Prozess"
}

在这种情况下我的问题是什么

【问题讨论】:

  • getProcesses() 是返回承诺的异步操作吗?
  • Yes getProcesses ist the Funktion which shoukd return the json
  • fetch() 是异步的,所以它不应该返回任何东西。 fetch().then() 是一个承诺,这意味着每当 fetch 完成时,请执行以下操作。所以稍微重构一下你的代码

标签: rest reactjs react-native fetch


【解决方案1】:

React render() 是 state 和 props 的纯函数。您不应该尝试执行异步 API 调用或修改渲染内部的状态;因此,如果您需要在组件中使用获取的数据,您可以将其加载到父组件中并将其作为props 传递,或者在组件内执行获取并将结果保存在组件中state。

这是一个使用组件state 的可能的简化实现示例:

class MyComponent extends Component {
  constructor(props) {
    super(props);
    this.getProcesses = this.getProcesses.bind(this);
  }

  componentDidMount() {
    this.getProcesses();
  }

  async getProcesses() {
    try {
      const response = await fetch('http://localhost:9000/processes');
      if (response.ok) {
        const processes = await response.json();
        this.setState({processes}); //this will trigger the render function with the new state
      } else {
        console.error(response.status);
      }
    } catch(e) {
      console.error(e);
    }
  }

  render() {
    const {processes} = this.state;
    return (
      <Text>
        {processes && processes.Prozess1}
      </Text>
    );
  }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-07-09
    • 1970-01-01
    • 2021-09-26
    • 2021-12-23
    • 1970-01-01
    • 2021-04-25
    • 1970-01-01
    • 2019-05-08
    相关资源
    最近更新 更多