来自REST Api的react-native fetch数据失败

时间:2017-04-10 13:23:56

标签: rest reactjs react-native fetch

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

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

1 个答案:

答案 0 :(得分:3)

React render()stateprops的纯函数。您不应该尝试执行异步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>
    );
  }
}
相关问题