BrowserRouter不会将历史记录传递给render

时间:2017-07-17 10:24:16

标签: react-router-v4

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内部可以按预期工作。

解决方案是什么?

1 个答案:

答案 0 :(得分:2)

我认为解决方案是使用render()

发送的函数参数中的历史对象
<Route path="/mylink" render={({history}) => (!isLoggedIn() 
    ? <Login/> 
    : <MyLink history={history}/>)} 
/>