Javascript 未在React中加载JSON api数据

Javascript 未在React中加载JSON api数据,javascript,json,reactjs,api,Javascript,Json,Reactjs,Api,因此,我对使用React是相当陌生的,我被指派从JSON API获取数据并将其显示在屏幕上。在练习提取数据时,一切都正常,我没有收到任何错误。有一次我试图从这个api获取数据 我的控制台中出现了这个巨大的错误(我确实删掉了一些eror消息,因为它实在是太大了) 未捕获类型错误:items.map不是函数 App.push../node_modules/react/cjs/react.development.js.Component.setState(react.development.js:35

因此,我对使用React是相当陌生的,我被指派从JSON API获取数据并将其显示在屏幕上。在练习提取数据时,一切都正常,我没有收到任何错误。有一次我试图从这个api获取数据

我的控制台中出现了这个巨大的错误(我确实删掉了一些eror消息,因为它实在是太大了)

未捕获类型错误:items.map不是函数

App.push../node_modules/react/cjs/react.development.js.Component.setState(react.development.js:356) App.js:16

所以我的问题是,为什么我可以从一个api而不是另一个api获取数据?其他api是否有问题,或者我是否做得不正确?我将在下面发布我的代码

从“React”导入React,{Component}

class App extends Component{
    constructor(props){
        super(props);
        this.state = {
            items:[],
            isLoaded: false
        };
    }
componentDidMount(){
取('https://www.hatchways.io/api/assessment/students')
.then(res=>res.json())
。然后(json=>{
这是我的国家({
isLoaded:是的,
项目:json,
})
});
}
render(){
const{isLoaded,items}=this.state;
如果(!已加载){
返回加载数据。。。;
}
否则{
返回(
    {items.map(item=>(
  • 名称:{item.name}
  • ))};
); } } } 导出默认应用程序;

看起来像
https://www.hatchways.io/api/assessment/students
API返回具有
students
属性的对象

因此,您的
是一个对象,而不是一个数组,这就是它没有
映射
功能的原因

要解决此问题,您的获取逻辑可以如下所示:

componentDidMount(){
      fetch('https://www.hatchways.io/api/assessment/students')
          .then(res=> res.json())
          .then(({ students }) => {
              this.setState({
                  isLoaded: true,
                  items: students,
              })
          });
  }

看起来像
https://www.hatchways.io/api/assessment/students
API返回具有
students
属性的对象

因此,您的
是一个对象,而不是一个数组,这就是它没有
映射
功能的原因

要解决此问题,您的获取逻辑可以如下所示:

componentDidMount(){
      fetch('https://www.hatchways.io/api/assessment/students')
          .then(res=> res.json())
          .then(({ students }) => {
              this.setState({
                  isLoaded: true,
                  items: students,
              })
          });
  }
componentDidMount(){
      fetch('https://www.hatchways.io/api/assessment/students')
          .then(res=> res.json())
          .then(({ students }) => {
              this.setState({
                  isLoaded: true,
                  items: students,
              })
          });
  }