繁体   English   中英

从REST Api获取反应本地数据失败

[英]react-native fetch data from REST Api fails

我想使用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"
}

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

React render()stateprops的纯函数。 您不应尝试执行异步API调用或在render内部修改状态; 因此,如果您需要在组件中使用提取的数据,则可以将其加载到父组件中并作为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>
    );
  }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM