JSON API数据未在React中加载

时间:2019-01-26 22:36:14

标签: javascript json reactjs api

因此,我对使用React还是比较陌生,并且已获得分配从JSON API提取数据并将其显示在屏幕上的任务。练习获取https://jsonplaceholder.typicode.com/users的数据时,一切工作正常,并且没有出现任何错误。一旦我尝试从该API https://www.hatchways.io/api/assessment/students获取数据。

我的控制台出现了这个大错误(我确实删除了一些错误消息,因为它确实很大)。

未捕获的TypeError:items.map不是函数

at App.render (App.js:34)
at finishClassComponent (react-dom.development.js:15141)
at updateClassComponent (react-dom.development.js:15096)
at beginWork (react-dom.development.js:15980)
at performUnitOfWork (react-dom.development.js:19102)
at workLoop (react-dom.development.js:19143)
at HTMLUnknownElement.callCallback (react-dom.development.js:147)
at Object.invokeGuardedCallbackDev (react-dom.development.js:196)
at invokeGuardedCallback (react-dom.development.js:250)
at replayUnitOfWork (react-dom.development.js:18350)
at renderRoot (react-dom.development.js:19261)
at performWorkOnRoot (react-dom.development.js:20165)
at performWork (react-dom.development.js:20075)
at performSyncWork (react-dom.development.js:20049)
at requestWork (react-dom.development.js:19904)
at scheduleWork (react-dom.development.js:19711)
at Object.enqueueSetState (react-dom.development.js:12936)
at

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(){
      fetch('https://www.hatchways.io/api/assessment/students')
          .then(res=> res.json())
          .then(json =>{
              this.setState({
                  isLoaded: true,
                  items: json,
              })
          });
  }


  render(){
      const {isLoaded, items} = this.state;
      if(!isLoaded){
          return <div>loading data...</div>;
      }

      else{           

          return(
              <div className="Data">
                  <ul>
                      {items.map(item=>(
                          <li key={item.students}>
                              name:{item.name}
                          </li>
                      ))};
                  </ul>                   
              </div>

          );
       }

  }

}

export default App;

1 个答案:

答案 0 :(得分:3)

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

因此,您的items是一个对象,而不是一个数组,这就是为什么它没有map函数的原因。

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

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