React:重定向到另一个页面

时间:2020-09-20 14:14:47

标签: reactjs react-router react-router-dom

我想有条件地重定向到另一个页面,这是我的代码:

render() {
    if (this.state.logged) {
      return <Redirect to="/admin" />;
    }
    console.log("Login");
    return (
      <div style={this.state.body}>
        <div style={this.state.box}>
          <br />
          <br />
          {this.getForm()}
          <br />
          <br />
        </div>
      </div>
    );
  }

问题是当条件满足并且应该重定向到admin.jsx时

我不断收到此错误:

Error: Invariant failed: You should not use <Redirect> outside a <Router>

这是我的app.js

import React from "react";
import logo from "./logo.svg";
import "./App.css";
import { link, Switch, Route } from "react-router-dom";
import Login from "./components/Login";

import Logout from "./components/Logout";
import Admin from "./components/Admin";

function App() {
  return (
    <switch>
      <Route exact path="/" component={Login} />
      <Route path="/admin" component={Admin} />
      <Route path="/user" component={Admin} />
      <Route path="/logout" exact component={Logout} />
    </switch>
  );
}

这是我的index.js:

import React from "react";
import ReactDOM from "react-dom";
import "./index.css";
import App from "./App";
import * as serviceWorker from "./serviceWorker";
import "bootstrap/dist/css/bootstrap.css";
import Login from "./components/Login";


ReactDOM.render(<Login />, document.getElementById("root"));

serviceWorker.unregister();

这是本教程中要执行的操作,我完全不知道为什么会这样。 请帮忙

2 个答案:

答案 0 :(得分:1)

<ul> <li> <h3>Lorem ipsum</h3> <p>lorem ipsum</p> </li> </ul> 中的Router包装整个应用,因为它为react-router-dom提供了上下文

Redirection

不在此处import React from "react"; import logo from "./logo.svg"; import "./App.css"; import { Link, Switch, Route, BrowserRouter as Router } from "react-router-dom"; import Login from "./components/Login"; import Logout from "./components/Logout"; import Admin from "./components/Admin"; function App() { return ( <Router> <Switch> <Route exact path="/" component={Login} /> <Route path="/admin" component={Admin} /> <Route path="/user" component={Admin} /> <Route path="/login" exact component={Login} /> <Route path="/logout" exact component={Logout} /> </Switch> </Router> ); } 呈现您的应用,并将您的登录名放在路由器中。

Login

答案 1 :(得分:1)

您必须使用Router提供的react-router-dom组件包装整个应用程序。如果您尝试使用Router之外的该库中的任何组件,则会收到该错误。

此外,这可能更像是一个优先事项,但是我认为我不会将Login组件作为应用程序的根。如果未登录,我将呈现App组件,然后重定向到Login

因此,您的index.js

中应该有类似的内容
import React from "react";
import "./index.css";
import App from "./App";
import * as serviceWorker from "./serviceWorker";
import "bootstrap/dist/css/bootstrap.css";
import { BrowserRouter as Router } from "react-router-dom";

ReactDOM.render(
    <Router>
       <App />
    </Router>,
    document.getElementById("root"));

serviceWorker.unregister();