gpt4 book ai didi

javascript - Navigate 不是 组件。 的所有子组件必须是

转载 作者:行者123 更新时间:2023-12-05 00:24:45 24 4
gpt4 key购买 nike

这个问题在这里已经有了答案:





Error "Error: A <Route> is only ever to be used as the child of <Routes> element"

(14 个回答)



Error: [PrivateRoute] is not a <Route> component. All component children of <Routes> must be a <Route> or <React.Fragment>

(16 个答案)


8 个月前关闭。




如果用户未登录且未设置 token ,我想重定向到另一个页面以使用react。为此,我尝试使用 react-router-dom Version: 6.0.2 中的 Navigate 选项,就像旧的 Redirect 选项一样。
但我得到错误:[Navigate] 不是一个组件。的所有子组件必须是 a 或

import "./App.css";
import { BrowserRouter, Route, Routes, Navigate } from "react-router-dom";

import AuthPage from "./pages/Auth";
import CompetitionPage from "./pages/Competitions";
import ConditionsPage from "./pages/Conditions";
import JudgesPage from "./pages/Judges";
import StartPage from "./pages/Start";
import WinnersPage from "./pages/Winners";
import AuthContext from "./context/auth-context";
import SubmissionPage from "./pages/Submission";

import MainNavigation from "./components/navigation/MainNavigation.js";
import React, { Component } from "react";

class App extends Component {
state = {
token: null,
userId: null,
};

login = (token, userId, tokenExpiration) => {
this.setState({ token: token, userId: userId });
};

logout = () => {
this.setState({ token: null, userId: null });
};

render() {
return (
<BrowserRouter>
<React.Fragment>
<AuthContext.Provider
value={{
token: this.state.token,
userId: this.state.userId,
login: this.login,
logout: this.logout,
}}
>
<MainNavigation />
<main className="main-content">
<Routes>
{!this.state.token && <Navigate from="/" to="/auth" exact />}
{this.state.token && (
<Navigate from="/" to="/competition" exact />
)}
{this.state.token && (
<Navigate from="/auth" to="/competition" exact />
)}
<Route exact path="/" element={StartPage} />
{!this.state.token && <Route path="/auth" element={AuthPage} />}
<Route path="/competition" element={CompetitionPage} />
{this.state.token && (
<Route path="/submission" element={SubmissionPage} />
)}
<Route path="/conditions" element={ConditionsPage} />
<Route path="/judges" element={JudgesPage} />
<Route path="/winners" element={WinnersPage} />
</Routes>
</main>
</AuthContext.Provider>
</React.Fragment>
</BrowserRouter>
);
}
}

export default App;

我不知道如何使用“导航”属性,因为我查找它并找到了 answer这说我只需要用“导航”替换旧的“重定向”属性。

最佳答案

据我所知,在 react-router v6 <Route>它是唯一可以成为 <Routes> 子组件的组件
您可以更改此代码

{this.state.token && (<Navigate from="/auth" to="/competition" exact />)}
<Route path="/auth" element={this.state.token ? <Navigate to="/competition" /> : AuthPage}

关于javascript - Navigate 不是 <Route> 组件。 <Routes> 的所有子组件必须是 <Route> 或 <React.Fragment>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70171991/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com