简体   繁体   English

单击一次按钮后如何获取axios.post信息

[英]How to get axios.post info after click a button once

When I want to get info from axios.post by clicking a button. 当我想通过单击按钮从axios.post获取信息时。 But now I wanted to click the button twice to display the info. 但是现在我想单击两次按钮以显示信息。 How should I do? 我应该怎么做?

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

This will not display the values you need. 这不会显示您需要的值。 Because at the time you are setting up the state inside click method your promise is not resolved. 因为在您设置click方法内部的状态时,您的承诺没有得到解决。

You can do something like this. 你可以做这样的事情。 Once a user click on button disable button till the axios post is done. 一旦用户单击禁用按钮,直到axios发布完成。 Then call setState so that you can see that data inside your div. 然后调用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>
           );
        }
    }

You've 2 options. 您有2个选择。

Bind your click event in the constructor: 将click事件绑定到构造函数中:

constructor(){
  this.click.bind(this)
}

And then your button becomes 然后你的按钮变成

<button onClick={this.click()}> click me </button>

or you can use es6 arrow functions to pass this too it, and declare your click functions like this: 或者您也可以使用es6箭头函数来传递它,并声明您的click函数,如下所示:

click = () => {

}

and then your button will become: 然后您的按钮将变为:

<button onClick={this.click}> click me </button>

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

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