我正在使用 React 18.0、React Router Dom (v6),并且我正在尝试实现 Paypal Checkout。它运行良好,付款后我将用户重定向到我的成功页面,其中包含用户的下载链接。问题是这个成功页面总是可以访问的。因此,我尝试在结帐后立即允许访问。之后,用户应该被重定向到主页。
我尝试这样做但没有成功:
import { useEffect } from "react"
import { useLocation, useNavigate } from "react-router-dom"
import { getInvoiceUrl } from "../services/invoiceService"
function Success() {
// Get the state from navigate on the Checkout page
let { state, pathname } = useLocation()
const navigate = useNavigate()
// Check the state in order to redirect the user to the homepage if the state is empty
useEffect(() => {
if (state === null || state === undefined) {
navigate("/")
return
}
// Clear the state after the user exits from the Success page
return navigate(pathname, { replace: true })
})
if (state === null || state === undefined) {
return
}
console.log("state:", state)
return (
<>
<div>
Thank you!
</div>
<div>
Abbiamo appena inviato un'email a
<span>
{state.email}
</span>
con in allegato la tua ricevuta (per favore, controlla la cartella SPAM se non dovessi vederla).
</div>
<div>
Puoi anche scaricare la ricevuta facendo click qui:
<a download href={getInvoiceUrl()}>
Download
</a>
</div>
</>
)
}
export default Success
最佳答案
对于 state === null || state === undefined
您缺少返回有效 JSX 的条件。此处返回 null
向 React 指示没有任何内容可渲染。
function Success() {
// Get the state from navigate on the Checkout page
const { state } = useLocation();
const navigate = useNavigate();
// Check the state in order to redirect the user to the homepage if the state is empty
useEffect(() => {
if (!state) {
navigate("/", { replace: true }); // <-- redirect to prevent access
return;
}
});
if (!state) {
return null; // <-- return valid JSX
}
return ( ... );
}
或者,要消除对 useEffect
的需要,请返回 Navigate
组件。
function Success() {
// Get the state from navigate on the Checkout page
const { state } = useLocation();
if (!state) {
return <Navigate to="/" replace />; // <-- return Redirect
}
return ( ... );
}
关于reactjs - 如何防止支付后直接进入成功页面?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71809647/