React路由器版本为4。
以下是我的代码中BrowserRouter
的用法:
import React from 'react';
import ReactDOM from 'react-dom';
import {Meteor} from 'meteor/meteor';
import {BrowserRouter, Route, Redirect, Switch} from 'react-router-dom';
import browserHistory from 'history';
import {Tracker} from 'meteor/tracker';
import Signup from '../imports/ui/Signup';
import MyLink from '../imports/ui/MyLink';
import NotFound from '../imports/ui/NotFound';
import Login from '../imports/ui/Login';
const history = browserHistory.createBrowserHistory();
const unathenticatedPages = ['/', '/signup'];
const athenticatedPages = ['/mylink'];
const isLoggedIn = () => {
return Meteor.userId() !== null;
};
const routes = (
<BrowserRouter>
<Switch >
<Route exact path="/" render={() => (isLoggedIn() ? <Redirect to="/mylink"/> : <Login/>)} />
<Route path="/signup" render={() => (isLoggedIn() ? <Redirect to="/mylink"/> : <Signup/>)} />
<Route path="/login" render={() => (isLoggedIn() ? <Redirect to="/mylink"/> : <Login/>)} />
<Route path="/mylink" render={() => (!isLoggedIn() ? <Login/> : <MyLink history={history}/>)} />
<Route path="*" component={NotFound} />
</Switch>
</BrowserRouter>
);
Tracker.autorun(() => {
const isAuthenticated = !!Meteor.userId();
console.log("isAuthenticated: ", isAuthenticated);
const pathname = history.location.pathname;
console.log("pathname: ", pathname);
const isUnathenticatedPage = unathenticatedPages.includes(pathname);
const isAthenticatedPage = athenticatedPages.includes(pathname);
if (isLoggedIn() && isUnathenticatedPage) {
history.replace('/mylink');
} else if (!isLoggedIn() && isAthenticatedPage) {
history.replace('/');
}
});
Meteor.startup(() => {
ReactDOM.render(routes, document.getElementById('app'));
});
我遇到的问题是BrowserRouter
的{{1}}在history
如上所述的情况下不会传递给渲染的组件。 render()
无法在this.props.history.replace('/notfound');
组件中运行。传递给MyLink
组件的history
实例似乎与MyLink
创建的实例不同。
但是在BrowserRouter
NotFound
内部可以按预期工作。
解决方案是什么?
答案 0 :(得分:2)
我认为解决方案是使用render()
<Route path="/mylink" render={({history}) => (!isLoggedIn()
? <Login/>
: <MyLink history={history}/>)}
/>