【发布时间】:2019-11-26 00:11:17
【问题描述】:
我创建了一个 react 应用,登录用户可以在其中使用 Stripe 升级他们的帐户。
我正在使用以下教程来实现 Stripe/Express:https://hackernoon.com/stripe-api-reactjs-and-express-bc446bf08301
stripeBtn.js
axios
.post("http://localhost:9000/payment", body)
.then(response => {
console.log(response);
alert("Payment Success");
})
.catch(error => {
console.log("Payment Error: ", error);
alert("Payment Error");
});
};
在 React 应用程序中测试 Stripe 购买是可行的,因为我在 Express 后端收到了 POST /payment 200 737.717 ms - 2261,并且可以在 Stripe 仪表板中看到测试付款数据。
现在我想在购买成功后推送到新视图,所以我尝试在购买后使用.push方法:
axios
.post("http://localhost:9000/payment", body)
.then(response => {
console.log(response);
// alert("Payment Success");
props.history.push('/prowelcome')
})
.catch(error => {
console.log("Payment Error: ", error);
alert("Payment Error");
});
};
但是,现在添加该行会导致显示 alert("Payment Error"); ,但是付款已成功发送到后端。
我也尝试过this.props.history.push(它在我的应用程序的其他地方也可以使用),但这些工作实例位于我的主 App.JS 文件中,我在其中为应用程序设置了状态和路由。
我想把这个 .js 函数引入 App.js,但是,教程中包含这个 axios/stripe 帖子的代码不是类或函数组件(我是一个相对的 n00b 反应),所以我我确定我将如何重构它以在应用程序 JS 中工作或如何修复 .push 方法。
stripeBtn.js(完整代码)
import React, { Fragment } from "react";
import StripeCheckout from "react-stripe-checkout";
import axios from "axios";
const stripeBtn = (props) => {
const publishableKey = process.env.STRIPE_PK;
const onToken = token => {
const body = {
amount: 9600,
token: token
}; axios
.post("http://localhost:9000/payment", body)
.then(response => {
console.log(response);
// alert("Payment Success");
this.props.history.push('/prowelcome')
})
.catch(error => {
console.log("Payment Error: ", error);
alert("Payment Error");
});
};
return (
<StripeCheckout
label="Go Premium" //Component button text
name="Business LLC" //Modal Header
description="Upgrade to a premium account today."
panelLabel="Go Premium" //Submit button in modal
amount={9600}
token={onToken}
stripeKey={publishableKey}
billingAddress={false}
/>
);
}
export default stripeBtn;
【问题讨论】:
-
我认为你可以使用钩子来做到这一点或将功能组件转换为一个类并创建一个状态来设置一个标志,其值将根据支付状态和状态改变时改变将调用 render 函数,您可以在其中进行检查并使用 Redirect 组件甚至 history.push
-
你能给我们展示一下整个组件吗?要在 props 中包含历史,您必须使用 withRouter(Comp) 包装组件或使用钩子: const history = useHistory();在组件中。
-
@Domino987 请查看我的编辑以获取
stripeBtn.js的完整代码
标签: javascript reactjs stripe-payments