如何使用<BrowserRouter>订阅组件的更改

时间:2019-11-19 14:43:36

标签: reactjs

我是React的新手,我想学很多东西。我有这样的导航:

<BrowserRouter >
  <Switch>
      <Route exact path="/" component={login} />
      <Route exact path="/home" component={home} />
      <Route component={Notfound} />
  </Switch>
</BrowserRouter>

,并且我想进行典型的验证,即如果我位于“登录”之类的组件中,则不会显示“页脚”或“页眉”。我认为获取当前组件可以使显示或不显示“页眉”或“页脚”组件具有逻辑。

我不确定哪种方法最好,我已经尝试了一些方法,但是遇到了“泄漏”问题,这是我的代码的一部分。

app.js
    import React from 'react';
    import { BrowserRouter, Route, Switch} from 'react-router-dom'
    import './App.css';
    import {  home,login } from "./pages";
    import { createBrowserHistory } from "history";
    const history = createBrowserHistory();
    // Listen to history changes.
    // You can unlisten by calling the constant (`unlisten()`).
    const unlisten = history.listen((location, action) => {
      console.log(action, location.pathname, location.state);
    });

    function App() {

      return (
        <BrowserRouter >
          <Switch>
           <Route exact path="/" component={login} />
           <Route exact path="/home" component={home} />
          </Switch>
        </BrowserRouter>
      );
    }

    export default App;

4 个答案:

答案 0 :(得分:1)

您的代码不正确。命名部分必须大写。将login更改为Login,并将home更改为Home

答案 1 :(得分:1)

首先,需要在switch语句之外呈现页眉和页脚,如下所示: (这将防止产生怪异的副作用和“泄漏”)

  <BrowserRouter >
    <Header />
    <Switch>
       <Route exact path="/" component={login} />
       <Route exact path="/home" component={home} />
    </Switch>
    <Footer />
  </BrowserRouter>

最好的解决方案是拥有多个switch语句。

头文件中的一个。 一为您的内容。 页脚文件中的一个。

或者在我工作过的许多公司中。 我们只是在页眉和页脚中有条件。

为了获得路由的上下文,您只需使用withRouter HoC。 像这样:

import { withRouter } from "react-router";

const Header = (props) => {
   const { match, location, history } = props;
   // This is all the data you will need for your conditions
   // return null if you want the header to be hidden
   return null;
}

export default withRouter(Header);

答案 2 :(得分:1)

好的,您在这里有2个疑问,一个是关于页眉,页脚,另一个是登录令牌

  

问题1(页眉,页脚)的解决方案:

路由正确,对于页眉页脚,我会想

export default Home = props => {
  return(
    <Header />
    //Content
   <Footer />
  )
}
  

问题2的解决方案:(如果用户已登录,请回家)

这种方法还可以帮助您在他单击主页上的“后退”按钮时返回主页,并且在他登录后也不会转到登录页面

export default Login = props => {
  const token = localStorage.getItem("tokenKey");
  if(token) {
    props.history.push("home");
  }
  return(
    //content
  )
}

如果我们遇到问题,例如登录页面被加载几秒钟,然后将其重定向到首页

  

为checkAuthentication创建一个单独的页面:

export default checkAuth = props => {
  const token = localStorage.getItem("tokenKey");
  return(
     {
       token ? <Home /> : <Login />
     }
  )
}

答案 3 :(得分:0)

React的最大价值是“组件”,因此请使用组件来解决您的问题。

如果定义并将其作为组件,则只需将它们渲染到需要的位置即可。我相信这比尝试针对不同的路线将其关闭要好得多。