Making REST calls from a react component

前端 未结 4 1840
醉酒成梦
醉酒成梦 2021-01-30 17:30

I am trying to make REST call from a react component and render the returned JSON data into the DOM

Here is my component

import React from \'react\';

ex         


        
4条回答
  •  萌比男神i
    2021-01-30 17:56

    Use the following instead. It will work: (You can also check the data if loaded in the console)

    
     constructor(props) {
            super(props);
            this.state = {
                items: []
            }
        }
    
     componentDidMount() {
            fetch('http://api/call')
                .then(Response => Response.json())
                .then(res => {
                    console.log(res);
                    this.setState({
                        items: res,
                    });
                })
                .catch(error => {
                    console.log(error)
                })
        }
    
    

    Then use the result stored in state during render to display as required.

提交回复
热议问题