gpt4 book ai didi

reactjs - React Router v4 获取当前位置

转载 作者:行者123 更新时间:2023-12-03 13:23:43 25 4
gpt4 key购买 nike

我刚刚开始使用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, {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'));
});

关于reactjs - React Router v4 获取当前位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43408406/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com