Javascript 如何在单击一次按钮后获取axios.post信息
当我想通过单击按钮从axios.post获取信息时。但是现在我想点击两次按钮来显示信息。我该怎么办Javascript 如何在单击一次按钮后获取axios.post信息,javascript,reactjs,react-native,Javascript,Reactjs,React Native,当我想通过单击按钮从axios.post获取信息时。但是现在我想点击两次按钮来显示信息。我该怎么办 class ButtonComponent extends React.Component { state = {display:"ini"}; rep = "ini"; click() { var self = this; axios.post("url", {}) .then((rep) => { self.rep = rep.d
class ButtonComponent extends React.Component {
state = {display:"ini"};
rep = "ini";
click() {
var self = this;
axios.post("url", {})
.then((rep) => {
self.rep = rep.data;
})
.catch((err) => {
self.rep = err;
})
this.setState({
display: this.rep
});
}
render() {
return (
<div>
<button onClick={this.click.bind(this)}> click me </button>
{this.state.display}
</div>
);
}
};
class按钮组件扩展了React.Component{
状态={显示:“ini”};
rep=“ini”;
单击(){
var self=这个;
post(“url”,{})
.然后((代表)=>{
self.rep=rep.data;
})
.catch((错误)=>{
self.rep=err;
})
这是我的国家({
显示:this.rep
});
}
render(){
返回(
点击我
{this.state.display}
);
}
};
您有两种选择
在构造函数中绑定单击事件:
constructor(){
this.click.bind(this)
}
然后你的按钮就变成了
<button onClick={this.click()}> click me </button>
然后您的按钮将变成:
<button onClick={this.click}> click me </button>
点击我
这将不会显示所需的值。因为在您设置click方法内部的状态时,您的承诺没有得到解决
你可以这样做。一旦用户单击按钮禁用按钮,直到完成axios post。然后调用setState,以便可以看到div中的数据
class ButtonComponent extends React.Component {
constructor(props){
super(props);
this.state = {
data: '',
isLoading: false,
};
this.click = this.click.bind(this);
}
click() {
this.setState({ isLoading: true });
axios.post("<MY_URL>:3900/find/rapinfo", {})
.then((response) => {
this.setState({ data: response.data, isLoading: false });
})
.catch((err) => {
this.setState({ data: err, isLoading: false });
});
}
render() {
return (
<div>
<button onClick={this.click} disabled={this.state.isLoading}> click me </button>
{this.state.data}
</div>
);
}
}
class按钮组件扩展了React.Component{
建造师(道具){
超级(道具);
此.state={
数据:“”,
孤岛加载:false,
};
this.click=this.click.bind(this);
}
单击(){
this.setState({isLoading:true});
axios.post(“:3900/find/rapinfo”,{})
。然后((响应)=>{
this.setState({data:response.data,isLoading:false});
})
.catch((错误)=>{
this.setState({data:err,isLoading:false});
});
}
render(){
返回(
点击我
{this.state.data}
);
}
}
这里有个错误。它应该是onClick={this.click}
当声明为click=()=>{}
时。干杯,伙计@雷德克泽梅里酒店
class ButtonComponent extends React.Component {
constructor(props){
super(props);
this.state = {
data: '',
isLoading: false,
};
this.click = this.click.bind(this);
}
click() {
this.setState({ isLoading: true });
axios.post("<MY_URL>:3900/find/rapinfo", {})
.then((response) => {
this.setState({ data: response.data, isLoading: false });
})
.catch((err) => {
this.setState({ data: err, isLoading: false });
});
}
render() {
return (
<div>
<button onClick={this.click} disabled={this.state.isLoading}> click me </button>
{this.state.data}
</div>
);
}
}