如何在React中通过Axios Post设置状态

bq3bfh9z  于 2022-11-05  发布在  iOS
关注(0)|答案(1)|浏览(123)

使用react和node,我正在通过axios post请求编写一个stripe支付处理器来setState clientSecret。后端的返回结果(即clientSecret的值)是正确的。我的问题在于前端:尽管可以通过console.log输出成功消息,但无法更新状态。我写了几个版本,但它们归结为两个示例,这两个示例都不起作用,但我将其粘贴如下:

示例1.js

..
constructor(props) {
    super(props);
    this.state = {
      clientSecret: ''
    };
  }

  async componentDidUpdate(prevProps) {
    if (this.props.cartItems !== prevProps.cartItems) {
      const data = {cart_items2: this.props.cartItems};
      var self = this;
      await axios.post('/create-payment-intent', data)
      .then(result => {
        console.log('Success in creating payment intent');
        self.result = result.data;
      })
      .catch(err => {
        console.log('Error in creating payment intent', err);
      })
      if(this.result) {
        this.setState({clientSecret: this.result.clientSecret}, () => { 
          console.log("this.state.clientSecret is", this.state.clientSecret);
        });
      }
    }
  }
..

示例2.js

import PaymentForm from './PaymentForm.js';
import OrderSummary from './OrderSummary.js';
import { Elements, ElementsConsumer } from '@stripe/react-stripe-js';
import { loadStripe } from '@stripe/stripe-js';
import './checkout.css';
import axios from 'axios';
const React = require('react');

class Payment extends React.Component {
..
constructor(props) {
    super(props);
    this.state = {
      clientSecret: ''
    };
  }

  componentDidUpdate(prevProps) {
    if (this.props.cartItems !== prevProps.cartItems) {
      const data = {cart_items2: this.props.cartItems};
      axios.post('/create-payment-intent', data)
      .then(result => {
        if(result.data) {
          console.log('Success in creating payment intent');
          this.setState({clientSecret: result.data.clientSecret}, () => { 
          console.log("this.state.clientSecret is", this.state.clientSecret);
          });
        }
      })
      .catch(err => {
        console.log('Error in creating payment intent', err);
      })
    }
  }
..
render() {

    return (
      <div>
      <Elements stripe={stripePromise}>
      <ElementsConsumer>
      {({ stripe, elements }) => (
        <div class="row">
          <div class="column">
            <PaymentForm stripe={stripe} elements={elements}/>
          </div>
          <div class="column">
            <OrderSummary cartItems={this.props.cartItems}/>
          </div>
        </div>

      )}
      </ElementsConsumer>
      </Elements>
      </div>
    )
  }

}

export default Payment;
mefy6pfw

mefy6pfw1#

您的应用可能正在使用尚未准备好的clientSecret。您能否分享完整的代码,并向我们展示您如何在前端应用中使用clientSecret

相关问题