![](/img/trans.png)
[英]How do I get data from Axios and return it from a Function Component in React?
[英]How to get a data from axios when component mount in react
我正在学习反应,我对在子组件中使用 axios 有点困惑。
所以这就是我需要得到一些 github repo 的最后一次提交和最后一个问题,并在引导卡中显示它。
所以我创建了组件来调用 github api。 当我调用组件时,错误发生如下:
警告:无法对未安装的组件执行 React state 更新。 这是一个无操作,但它表明您的应用程序中存在 memory 泄漏。 要解决此问题,请取消 componentWillUnmount 方法中的所有订阅和异步任务。 在卡片上 (http://localhost:3000/static/js/main.chunk.js:649:5)
我的子组件是这样的:
constructor(props){
super(props);
this.state = {
isSelected: false,
lastCommit : null,
lastIssue : null,
}
}
getLastCommit= (repo, owner) => {
axios
.get(`https://api.github.com/repos/${owner}/${repo}/commits?per_page=1`)
.then((result)=>{
console.log(result.data);
this.setLastCommit(result.data[0]);
});
}
setLastCommit=(commit) => {
this.setState({
lastCommit : commit
})
}
getLastIssue=(repo, owner)=>{
axios
.get(`https://api.github.com/repos/${owner}/${repo}/issues?per_page=1`)
.then((result) => {
this.setLastIssue(result.data[0])
});
}
setLastIssue= (issue) => {
this.setState({
lastIssue : issue
});
}
// get commit and issues
// these functions below are functions that add and remove lists.
onSelectRepo = (e) => {
const{id, selectRepo} = this.props;
selectRepo(id);
this.getLastCommit(this.props.repoName ,this.props.Author);
this.getLastIssue(this.props.repoName ,this.props.Author);
}
onDeleteRepo = (e) => {
const {id, deleteRepo} = this.props;
deleteRepo(id);
}
render() {
const{ lastIssue, lastCommit } = this.state;
const { repoName, Author, URL, isSelected} =this.props;
return (
<div className="m-2">
<div className="card">
<div className="card-header d-flex justify-content-between" >
<h6>{repoName}</h6>
{
isSelected?
<button onClick={this.onDeleteRepo} className="btn btn-sm btn-outline-secondary"><i className="fas fa-minus"></i></button>
:<button onClick={this.onSelectRepo} className="btn btn-sm btn-outline-secondary"><i className="fas fa-plus"></i></button>
}
</div>
<div className="card-body">
<p>
<hr/>
<strong>Last Issue:</strong> {lastIssue} <br/>
<strong>Last Commit: </strong> {lastCommit}
</p>
</div>
所以我需要从 github 获取最后一次提交和最后一个问题,当组件创建时,它将运行。
我该如何处理和运行它。
提前致谢。
您可以使用ComponentDidMount()
。
或者,如果你使用 React 16.8+,你可以使用useEffect()
钩子
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.