小能豆

Navigate 不是 <Route> 组件。<Routes> 的所有子组件都必须是 <Route> 或 <React.Fragment>

javascript

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

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;

我不确定如何使用“Navigate”属性,因为我查找了它并找到了一个答案,它说我只需要用“Navigate”替换旧的“Redirect”属性。


阅读 51

收藏
2024-06-25

共1个答案

小能豆

据我所知,在 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}
2024-06-25