javascript - react js 获取 API

标签 javascript reactjs fetch-api

我正在学习 React.js 并尝试像这样获取 API

constructor() {
    super();

    this.state = {person: []};
}

componentDidMount() {
    fetch('https://randomuser.me/api/?results=500', {mode: 'no-cors'})
            .then(results => {
                return results.json();
            })
            .then(data => {
                let person = (data.results || []).map((pic) => {
                    return(
                            <div key={pic.results}></div>
                            )
                })

                this.setState({person: person});
                console.log("state", this.state.person);
            })
}

render() {

    return (
            <div>
                {this.state.person}
            </div>
    );
}

这是我得到的错误

http://prntscr.com/k36ggq

我是这方面的新手,所以如果有人能帮助我,那就太好了。谢谢

最佳答案

尝试按如下方式设置标题。 https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS 您只需删除代码中的 mode: 'no-cors'

componentDidMount() {
    fetch('https://randomuser.me/api/?results=500')
    .then(response =>  response.json())
    .then(resData => {
       //console.log(JSON.stringify(resData))
       //do your logic here       
       //let person = resData.results
       this.setState({ person: resData.results }); //this is an asynchronous function
    })
}

render(){

  return(
  <div>
    { 
      this.state.person.map((personRecord) => {
        return <div key={personRecord.id.value}> {personRecord.name.first} </div>
      })
    }
  </div>
  )
}

//sample result json 
{
"results": [ //we already fetched the results array of object from resData
        {
            "gender": "female",
            "name": {
                "title": "mrs",
                "first": "astrid",
                "last": "jørgensen"
            },
            "location": {
                "street": "2675 strandgårdsvej",
                "city": "hurup thy",
                "state": "danmark",
                "postcode": 63288,
                "coordinates": {
                    "latitude": "-27.6956",
                    "longitude": "104.8135"
                },
                "timezone": {
                    "offset": "+5:30",
                    "description": "Bombay, Calcutta, Madras, New Delhi"
                }
            },
            "email": "astrid.jørgensen@example.com",
            "login": {
                "uuid": "25ab4c50-9a8c-48bc-a276-acae2209aa19",
                "username": "happymouse810",
                "password": "journey",
                "salt": "OGXHTU6k",
                "md5": "5c659a3d97b081fc18f0bf94f246751d",
                "sha1": "407020d4230121788180244775edd6fbea56c375",
                "sha256": "0cc94ec5d89f71903c9f74dcd12253240b1269e75a3ca67eae3f4d578e47d3f8"
            },
            "dob": {
                "date": "1978-03-28T17:31:08Z",
                "age": 40
            },
            "registered": {
                "date": "2017-04-19T14:15:02Z",
                "age": 1
            },
            "phone": "10566067",
            "cell": "24745172",
            "id": {
                "name": "CPR",
                "value": "295410-3587"
            },
            "picture": {
                "large": "https://randomuser.me/api/portraits/women/12.jpg",
                "medium": "https://randomuser.me/api/portraits/med/women/12.jpg",
                "thumbnail": "https://randomuser.me/api/portraits/thumb/women/12.jpg"
            },
            "nat": "DK"
        }
    ]
}

//By using this way we can able to get the result, but it just delays
fetch('https://randomuser.me/api/?results=500')
.then(response =>  response.json())
.then(resData => console.log(resData))

关于javascript - react js 获取 API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51204735/

相关文章:

javascript - 单击按钮在新选项卡上打开链接

javascript - useState 和 props 的变化

reactjs - 面包屑 react 代码不起作用,我该如何修复它?

json - <不可读> 对于 100000 字节或以上的 POST 正文长度,也适用于 blob/FormData

javascript - Fetch Api 无法从 PHP 服务器获取 Session

authentication - 是否可以下载音频文件并使用 React Native Expo 播放?

php - 使用正则表达式获取除指定类名之外的所有链接

javascript - 无法调用 jQuery 函数

javascript - react -chartjs-2 : Pie Chart tooltip percentage

javascript - React Leaflet : Get objects from MongoDB to Leaflet map as markers (using node. js 和 express)