简体   繁体   中英

how to bind “this” when passing a React prop into axios.post

I am using the react-paypal-express-checkout element. There is a method for passing functions on successful payment. In this method, I want to make an axios.post where in I pass data to a server.

The data is in the state of the parent component, and is passed like so:

<Pay value={this.state.value} />

My axios.post in the child ( <Pay /> ) element is:

export default class Pay extends React.Component {
  render() {
    const onSuccess = payment => {
      axios.post(
        "http://localhost:3000/updateValue", {this.props.value}
      );
    };
    return (
      <div>
        <PaypalExpressBtn
          onSuccess={onSuccess}  
        />
      </div>
    );
  }
}

The error given for this.props.value is that this is a reserved word. I assume that this is not bound properly, but I don't know how to do it. Any help is appreciated!

The problem isn't related to function binding. onSuccess is an arrow, it cannot and shouldn't be bound. {this.props.value} is incorrect syntax for object literal.

In case value contains data that should be posted, it should be:

  axios.post(
    "http://localhost:3000/updateValue", {data: this.props.value}
  );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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