繁体   English   中英

通过API调用使用React

[英]Using React with API calls

我收到了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请求是否良好,也不确定如何测试。

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

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});
    });  
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM