reactjs - 在反应中使用 Onclick 事件更新 Axios Url
问题描述
我正在API
使用axios
:
constructor(props) {
super(props);
this.state = {
url:[],
title:'anime',
limit:6,
}
this.more_button.bind(this)
}
componentDidMount() {
//limit is on the end of the url
const limit= this.state.limit
axios.get(`http://api.giphy.com/v1/gifs/search?q=sth&api_key=MY_KEY&limit=` + limit)
.then(res => {
const url= res.data.data;
this.setState({ url });
})
}
limit
当我点击一个按钮时,我想改变;我这样做:
more_button=()=>{
this.setState((previousState) => {
return { limit: previousState.limit + 6 };
});
this.componentDidMount();
}
问题是我应该单击该按钮两次才能工作。
渲染部分:
render(){
return(
<div className="container">
<button
onClick={this.more_button} >
Give me More!
</button>
)
}
}
解决方案
ComponentDidMount 是一个生命周期方法。不要手动调用这个函数,试试下面的代码。
componentDidMount() {
//limit is on the end of the url
this.apiCall();
}
apiCall() {
const limit= this.state.limit
axios.get(`http://api.giphy.com/v1/gifs/search?q=sth&api_key=MY_KEY&limit=` + limit)
.then(res => {
const url= res.data.data;
this.setState({ url });
})
}
more_button = () => {
this.setState((previousState) => {
return { limit: previousState.limit + 6 };
});
this.apiCall();
}
更改您的渲染 onClick 方法,例如:
onClick={()=>this.more_button}
最后在构造函数中添加额外的行:
constructor(props) {
super(props);
this.state = {
url:[],
title:'anime',
limit:6,
}
this.apiCall = this.apiCall.bind(this);
this.more_button = this.more_button.bind(this);
}
推荐阅读
- eclipse - org.mockito.internal.stubbing.ConsecutiveStubbin
- azure - AD 身份验证失败时如何导航到正确的未授权页面
- python - Django:不同模型中的全局搜索 - 发布结果不出现
- amazon-web-services - 了解评估期和警报数据点
- huawei-mobile-services - 由于连接问题,华为 AppGallery 拒绝了我的申请草稿
- r - 根据以前的表现填充R中的缺失值
- azure-devops - msbuild 的原因是什么,你在我的计算机上本地输出的输出与在 Azure Devops 上输出的输出不同
- python - 为 sqlalchemy 动态创建 case 语句
- mongodb - MongoDB 多个子查询
- javascript - 获取对象数组中对象给定键的值