Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/hadoop/6.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Reactjs 使用axios.get时出错。使用baseUrl创建方法_Reactjs_Get_Axios_Httprequest - Fatal编程技术网

Reactjs 使用axios.get时出错。使用baseUrl创建方法

Reactjs 使用axios.get时出错。使用baseUrl创建方法,reactjs,get,axios,httprequest,Reactjs,Get,Axios,Httprequest,我试图从react中的随机用户API创建一个应用程序,并将axios库用于HTTP请求。我使用axios.create为基本API创建了一个单独的文件,文件代码如下: import axios from 'axios' export default axios.create({ baseURL: `http://jsonplaceholder.typicode.com`, }); 然后我在另一个文件中使用它来发出GET请求,并将数据存储在componentdidMount上的状态中,以

我试图从react中的随机用户API创建一个应用程序,并将axios库用于HTTP请求。我使用axios.create为基本API创建了一个单独的文件,文件代码如下:

import axios from 'axios'

export default axios.create({
  baseURL: `http://jsonplaceholder.typicode.com`,
}); 
然后我在另一个文件中使用它来发出GET请求,并将数据存储在componentdidMount上的
状态中,以便我可以访问UI中的数据

import React from "react";
import API from "../api";
export default class PersonList extends React.Component {
  state = {
    persons: []
  };
  componentDidMount() {
    API
      .get('/').then((data) => {
      const persons = data.data;
      this.setState({ persons });
      console.log(this.state.persons);
    });
  }
  render() {
    const { persons } = this.state;
    console.log('Stato',persons)
    return (
      <ul>
        {persons.map((person) => (
          <li key={person.id}>{person.name}</li>
        ))}
      </ul>
    );
  }
}

从“React”导入React;
从“./API”导入API;
导出默认类PersonList扩展React.Component{
状态={
人员:[]
};
componentDidMount(){
美国石油学会
.get('/')。然后((数据)=>{
const persons=data.data;
这个.集合状态({persons});
console.log(this.state.persons);
});
}
render(){
const{persons}=这个州;
控制台日志('Stato',人员)
返回(
    {persons.map((person)=>(
  • {person.name}
  • ))}
); } }

但是它不起作用,因为状态中没有填充用户数据,因此.map()函数抛出了一个错误。

您遇到这个错误是因为您使用的URL。在您的示例中,使用
https://jsonplaceholder.typicode.com
作为
componentDidMount
中的端点,但这不会返回任何占位符用户数据。我相信你是想用
https://jsonplaceholder.typicode.com/users


我这里有一个工作示例:。请注意,我只需将
/
中的
/
更改为
/users

作为后续建议,如果您尝试迭代的列表没有您期望的形状,则使用类似
的lodash
ramda
可以帮助清除
映射所引发的错误。当然,这并不能解决您真正的问题,但它可以减少在您面前爆发的错误类型。我会相应地更新我的沙盒来展示一个例子。谢谢,伙计,这意味着一个大问题。很高兴我能帮忙!