【问题标题】:Using React with API calls将 React 与 API 调用一起使用
【发布时间】:2018-02-08 23:59:25
【问题描述】:

我收到Uncaught TypeError: (0 , f.default) is not a function

items component

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;

item utils

export const fetchItemsAPI = (url) => {
fetch(url).then((res) => {
      return res.json();
    }).then(data=>{
      return({
        champion: data.id,
        name:data.name
      });
    });
};

我不确定请求是否通过,因为 api 在我使用时有效。我不确定 util 请求是否良好,我不确定如何测试它。

【问题讨论】:

  • promise 不返回值,但其他 promise :)

标签: javascript reactjs api


【解决方案1】:

您必须返回 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 回调以在出现错误时更新状态。永远记住,promise 不会返回值,只是其他可以解析为这些值的 promise,就像 WillomGfx 在他的评论中所说的那样
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-04-29
  • 1970-01-01
  • 2016-11-20
  • 2018-07-18
  • 2017-01-13
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多