1
的陣營路由器的版本是4 這裏是BrowserRouter
我的代碼中使用: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
的history
不在上述render()
之內時傳遞給呈現的組件。 this.props.history.replace('/notfound');
在MyLink
組件內不起作用。傳遞給MyLink
組件的history
實例似乎不像BrowserRouter
創建的那樣。 但是在NotFound
內,一個this.props.history.replace('/...');
將按預期工作。
會是什麼解決方案?
這是關於這一主題,實際上顯示瞭如何有效地做到這一點的例子是唯一的答案發送。 +1,解決了我的問題。 –