使用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;
1条答案
按热度按时间mefy6pfw1#
您的应用可能正在使用尚未准备好的
clientSecret
。您能否分享完整的代码,并向我们展示您如何在前端应用中使用clientSecret
?