React(v4) - 检查用户是否访问任何路由器

时间:2017-08-30 02:00:55

标签: reactjs meteor react-router

我正在尝试让我的应用程序将用户重定向到登录页面,如果它没有检测到Meteor.userId(),并且如果他们确实有,则将其重定向到主页。我现在正在努力解决的问题是在用户访问路径时(无论路径如何)运行一个简单的console.log函数。如何从管理所有路由和组件的文件中执行此操作,而无需在每个组件中插入样板代码。

import { Meteor } from "meteor/meteor"
import React from "react";
import { withRouter, Switch, BrowserRouter, Route, Redirect, Link } from "react-router-dom";
import { Tracker } from "meteor/tracker";

import Login from "../ui/authentication/Login";
import Signup from "../ui/authentication/Signup";
import Home from "../ui/Home";
import searchNotes from "../ui/searchNotes"
import Note from "../ui/Note";
import fullSize from "../ui/fullSize"
import userProfile from "../ui/userProfile";
import AddNote from "../ui/AddNote";
import questions from "../ui/questions"
import NotFound from "../ui/NotFound";

export default class Routes extends React.Component{
  componentDidMount() {
    console.log("rendering page")
  }
  render(){
    return (
      <div>
        <BrowserRouter>
          <Switch>
            <Login path="/login" />
            <Signup path="/signup" />
            <Route path="/" component={Home} exact/>
            <Route path={`/searchNotes/:subject`} component={Note} />
            <Route path={`/searchNotes`} component={searchNotes} />
            <Route path={`/fullSize/:noteId`} component={fullSize}/>
            <AddNote path="/addNote"/>
            <Route path="/questions" component={questions} />
            <Route component={userProfile} path={`/users/:userId`} />
            <NotFound />
          </Switch>
        </BrowserRouter>
      </div>
    )
  }
}

另外,我尝试了export default withRouter(Routes),因此我可以将人员重定向到新页面,但是当我这样做时,它会在浏览器中返回错误,"Uncaught TypeError: Cannot read property 'route' of undefined"如果您知道如何解决这个问题,非常感谢。谢谢!

0 个答案:

没有答案