未捕获的错误: [元素] 不是<Route>组件。的所有组件子级<Routes>必须是 或 <Route> <React.Fragment>



我试图集成strip API密钥,但无法在新的react-router-dom版本中找到解决方案

这是完整的错误

上述错误发生在组件中:

at Routes (http://localhost:3000/static/js/bundle.js:81119:5)
at Router (http://localhost:3000/static/js/bundle.js:81052:15)
at BrowserRouter (http://localhost:3000/static/js/bundle.js:79861:5)
at App (http://localhost:3000/main.79cc3231add2da1b35a8.hot-update.js:89:63)
at Provider (http://localhost:3000/static/js/bundle.js:74963:5)

考虑在树中添加一个错误边界,以自定义错误处理行为。参观https://reactjs.org/link/error-boundaries以了解有关错误边界的更多信息。

这是我的Appjs保护路由代码:

import { Elements } from "@stripe/react-stripe-js";
import { loadStripe } from "@stripe/stripe-js";
useEffect(() => {
store.dispatch(loadUser());
getStripeApiKey();
}, []);
useEffect(() => {
const stripePromise= loadStripe(stripeApiKey);
}, [stripeApiKey]);

<Route element={<ProtectedRoute />}>
<Route path="/account" element={<Profile />} />
<Route path="/me/update" element={<ProfileEdit />} />
<Route path="/password/update" element={<UpdatePassword />} />
<Route path="/login/shipping" element={<Shipping />} />
<Route path="/order/confirm" element={<ConfirmOrder />} />
{stripeApiKey && (
<Elements stripe={stripePromise}>
<Route path="/order/payment" element={<Payment />} />
</Elements>
)}
</Route>

我的受保护路线代码

const ProtectedRoute = () => {
const { loading, isAuthenticated, user } = useSelector((state) => state.user);
const location = useLocation();
if (isAuthenticated == false) {
return <Navigate to="/account" state={{ from: location }} />;
}
return <Outlet />;
};
export default ProtectedRoute;

问题

这个问题是,您正在Routes组件中渲染以外的RouteReact.Fragment

{stripeApiKey && (
<Elements stripe={stripePromise}>
<Route path="/order/payment" element={<Payment />} />
</Elements>
)}

Elements组件两者都不是,并且未通过不变量检查。

解决方案

将其重构为类似于ProtectedRoute组件的布局路由组件。

示例:

import { Outlet, Navigate } from 'react-router-dom';
const StripeLayout = ({ stripeApiKey }) => {
return stripeApiKey
? <Outlet />
: <Navigate to="/" replace />
};

<Route element={<ProtectedRoute />}>
<Route path="/account" element={<Profile />} />
<Route path="/me/update" element={<ProfileEdit />} />
<Route path="/password/update" element={<UpdatePassword />} />
<Route path="/login/shipping" element={<Shipping />} />
<Route path="/order/confirm" element={<ConfirmOrder />} />
<Route element={<StripeLayout {...{ stripeApiKey }} />}>
<Route
path="/order/payment"
element={(
<Elements stripe={stripePromise}>
<Payment />
</Elements>
)}
/>
</Route>
</Route>

由于的这行代码,您出现了错误

{stripeApiKey && (
<Elements stripe={stripePromise}>
<Route path="/order/payment" element={<Payment />} />
</Elements>
)}

只有Route或React.Frage可以是Routes组件的子级。但在您的情况下,如果stripePiKey是真的,那么您正在呈现与新的react路由器v6规则相矛盾的Elements组件

就像你在评论中问的那样,你想包装你的支付方式

<Route path="/order/payment" element={<Elements stripe={stripePromise}><Payment /></Elements} />

最新更新