加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

reactjs – React Router v4获取当前位置

发布时间:2020-12-15 05:05:58 所属栏目:百科 来源:网络整理
导读:我刚开始使用react-router V4,我想知道如何获取路由器的当前位置 这是我的源代码 import {Meteor} from 'meteor/meteor';import React,{Component} from 'react';import ReactDOM from 'react-dom';import createHistory from 'history/createBrowserHistory
我刚开始使用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,如果没有它,我会很感激.

谢谢,迈克尔.

您可以使用 withrouter HOC.它会在路径发生变化时重新渲染包裹的组件.这是一个例子 –
import {Meteor} from 'meteor/meteor';
import React,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.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'));
});

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读