React Router v4获取当前位置

时间:2017-04-14 09:00:00

标签: reactjs meteor react-router react-router-v4

我刚刚开始使用react-router V4,我想知道如何获取路由器的当前位置

这是我的源代码

import {Meteor} from 'meteor/meteor';
import React, {Component} from 'react';
import ReactDOM from 'react-dom';
import createHistory from 'history/createBrowserHistory'
import {Route, BrowserRouter as Router, Switch} from 'react-router-dom'
import {Tracker} from 'meteor/tracker';

import Signup from '../imports/ui/signUp';
import Link from '../imports/ui/link';
import Login from '../imports/ui/login';
import NotFound from '../imports/ui/notFound';

const history = createHistory();
const unauthenticatedPages = ['/', '/signup'];
const authenticatedPages = ['/links'];

const routes = (
    <Router history={history}>
        <Switch>
            <Route exact path="/" component={Login}/>
            <Route exact path="/signup" component={Signup}/>
            <Route path="/links" component={Link}/>
            <Route component={NotFound}/>
        </Switch>
    </Router>
);
Tracker.autorun(() => {
    const unlisten = history.listen((location, action) => {
        // location is an object like window.location
        console.log(action, location.pathname, location.state)
    })

    const isAuthenticated = !!Meteor.userId();
    console.log('location: ', location.pathname);
    //const pathName =
});

Meteor.startup(() => {
    ReactDOM.render(routes, document.getElementById('app'));
}); 

我根据react-router文档尝试使用历史记录,但我没有获得该位置。

如何获取路线的当前位置?

我不使用redux,如果没有它,我会很感激。

谢谢,迈克尔。

3 个答案:

答案 0 :(得分:8)

您可以使用withrouter HOC进行此操作。它会在路径发生变化时重新渲染包裹的组件。这是一个例子 -

for obj in list_objects:
    obj.set_ID()

答案 1 :(得分:2)

非常好的帮助感谢 - 无论您是否在经过身份验证的网页上保持实时更新,您都可以按如下方式修改ChangeTracker:

const ChangeTracker = withRouter(({match, location, history}) => {
  const pathName = location.pathname;
  isUnauthenticatedPage = unauthenticatedPages.includes(pathName);
  isAuthenticatedPage = authenticatedPages.includes(pathName);

  return false;
});

你的Tracker.autorun可能看起来像:

Tracker.autorun(()=>{
  const isAuthenticated = !!Meteor.userId();
    if (isAuthenticated){
      if (isUnauthenticatedPage){
        history.push('/links');
      }
    }else{
      if (isAuthenticatedPage) {
        history.push('/');
      }
    }
});

答案 2 :(得分:1)

您可以通过history.location和路由名history.location.pathname从路由器v4获取当前位置。您可以在github React Router Training上的官方反应路由器文档中找到有关它的更多详细信息。

所以你的代码应该是这样的:

&#13;
&#13;
import {Meteor} from 'meteor/meteor';
import React, {Component} from 'react';
import ReactDOM from 'react-dom';
import createHistory from 'history/createBrowserHistory'
import { Route, Router, Switch } from 'react-router-dom'
import {Tracker} from 'meteor/tracker';

import Signup from '../imports/ui/signUp';
import Link from '../imports/ui/link';
import Login from '../imports/ui/login';
import NotFound from '../imports/ui/notFound';

const history = createHistory();
const unauthenticatedPages = ['/', '/signup'];
const authenticatedPages = ['/links'];

const routes = (
    <Router history={history}>
        <Switch>
            <Route exact path="/" component={Login}/>
            <Route exact path="/signup" component={Signup}/>
            <Route path="/links" component={Link}/>
            <Route component={NotFound}/>
        </Switch>
    </Router>
);
Tracker.autorun(() => {
    const isAuthenticated = !!Meteor.userId();
    const pathname = history.location.pathname;
    //Now you can do whatever you want here
});
&#13;
&#13;
&#13;

重要!将历史作为道具传递给BrowserRouter会发出警告,因为默认情况下,BrowserRouter使用其历史版本并忽略您传递的历史记录,因此要防止出现此警告,您应该使用{ Router } from 'react-router-dom'而不是比BrowserRouter而且一切都按照你期望的方式运作。

相关问题