【问题标题】:React Router v4 get current locationReact Router v4 获取当前位置
【发布时间】:2017-09-10 12:41:18
【问题描述】:

我刚开始使用 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,如果没有它,我将不胜感激。

谢谢,迈克尔。

【问题讨论】:

  • 在您的路由组件中,您可以将匹配道具传递给子组件并访问那里的位置。这种方法用于链接路由组件

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


【解决方案1】:

您可以为此使用withrouter HOC。每当路由更改时,它将重新渲染包装的组件。这是一个例子 -

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 {withRouter} from 'react-router'
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
ChangeTracker = withRouter(({match, location, history}) => {
    console.log(action, location.pathname, location.state);
    return false;
}),
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>
        <ChangeTracker />
    </Router>
);

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

【讨论】:

    【解决方案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('/');
          }
        }
    });
    

    【讨论】:

      【解决方案3】:

      您可以通过 history.location 从 react router v4 获取您当前的位置,路径名可以使用 history.location.pathname。您可以在 githubReact Router Training 上的官方 react 路由器文档中找到有关它的更多详细信息。

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

      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
      });

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

      【讨论】:

        猜你喜欢
        • 2018-11-03
        • 2016-12-26
        • 2018-12-13
        • 1970-01-01
        • 2017-08-29
        • 2017-10-26
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多