我刚开始使用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')); });
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。