简体   繁体   中英

react-native fetch data from REST Api fails

I want to fetch data from a different Server with a REST API.

I do this:

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

In the render function I have this:

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

and this

        {JSON.stringify(getProcesses()) }

no one of thesse two examples returns something

The rest API should return this:

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

whats my problem in this case

React render() is a pure function of state and props . You shouldn't try to perform asynchronous API calls or modify state inside render; so if you need to use fetched data in your components, you can either load it in the parent component and pass it as props , or perform the fetch inside the component and save the result in your component state .

Here's an example of a possible, simplified implementation using the component 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>
    );
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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