问题
I need redirect page after it load and get param from URL. I can do by button click. But how I can make page redirect automatic after page have get param from URL (without user input)?
Thanks!
const handleClick = async (event) => {
const stripe = await stripePromise;
const { error } = await stripe.redirectToCheckout({
param,
});
}
const param = new URLSearchParams(window.location.search).get('param');
const Page = () => {
React.useEffect(() => {
window.scrollTo(0, 0);
}, []);
return (
<section >
<button role="link" onClick={handleClick}>
Press
</button>
</section>
);
};
export default Page;
回答1:
You could probably just use your useEffect hook there to redirect the page, instead of using the onClick handler. e.g.
const handleLoad = async () => {
const stripe = await stripePromise;
const { error } = await stripe.redirectToCheckout({
param,
});
}
const param = new URLSearchParams(window.location.search).get('param');
const Page = () => {
React.useEffect(() => {
handleLoad();
}, []);
return null;
};
export default Page;
Though, you don't really even need to load up React for any of this. You could just make this page a static html page with a script tag that does the redirect logic, or something similar to that.
After further discussion, we found out that in order for this stripe stuff to work on Safari-mobile, we needed to wait for the page's load event before calling handleLoad(), so something like this:
const handleLoad = async () => {
const stripe = await stripePromise;
const { error } = await stripe.redirectToCheckout({
param,
});
}
const param = new URLSearchParams(window.location.search).get('param');
window.addEventListener('load', () => handleLoad())
回答2:
You're going to want to parse those query parameters in the init/load handler. You can see an example of this here. Note that the event listener on DOMContentLoaded
kicks everything off. An example of this in action can be seen here.
I noticed that your code uses param
in the Checkout redirect directly. If param
is a checkout session that you should be generating these on demand, not sending them in emailed links etc, as they are short-lived. In the example above, the code
param is read and use to generate a new checkout session via a fetch
and then that is used for the redirect.
来源:https://stackoverflow.com/questions/62971083/how-to-call-function-after-urlsearchparam