Javascript 使用React和API调用

Javascript 使用React和API调用,javascript,reactjs,api,Javascript,Reactjs,Api,我得到的uncaughttypeerror:(0,f.default)不是函数 项目组件 class Items extends React.Component{ constructor(props){ super(props); this.state = { itemList: [], }; this.fetchItems = this.fetchItems.bind(this); } fetchItems(){ const url ="url" #api goes here; this.

我得到的
uncaughttypeerror:(0,f.default)不是函数

项目组件

class Items extends React.Component{
constructor(props){
super(props);
this.state = {
  itemList: [],
};
this.fetchItems = this.fetchItems.bind(this);
}
fetchItems(){
const url ="url" #api goes here;
this.setState({data: utilAPI(url)});
}

render(){
  return(
      <div className="jumbotron mx-auto jumbo-about">
        {this.fetchItems()}
        {console.log(this.state)}
        <p>{this.state.itemList}</p>
      </div>
    );
}
}

export default Items;

我不确定请求是否通过,因为api在我使用它时起作用。我不确定util请求是否正确,也不确定如何测试它。

您必须返回fetch调用的结果。然后用它来设置状态

const fetchItemsAPI = (url) => {
  return fetch(url).then((res) => {
      return res.json();
    });
};

fetchItems(){
  const url ="url" #api goes here;
  fetchItemsAPI(url)
    .then(data => {
      //Here you can manipulate the json data
      this.setState({data});
    });  
}

承诺不返回值,但其他承诺:)我看到了我犯的错误,我试图在chrome控制台中键入它,并得到一个CORS错误。这是您必须在后端解决的问题。当您解决CORS问题时,这应该会起作用。注意:您还可以添加一个
catch
回调,以在出现错误时更新状态。永远记住,承诺不会回报价值观,只是其他承诺会满足这些价值观,就像WillomGfx在评论中说的那样
const fetchItemsAPI = (url) => {
  return fetch(url).then((res) => {
      return res.json();
    });
};

fetchItems(){
  const url ="url" #api goes here;
  fetchItemsAPI(url)
    .then(data => {
      //Here you can manipulate the json data
      this.setState({data});
    });  
}