React Router v4 重定向无法重定向 [英] React Router v4 Redirect fails to redirect

查看:43
本文介绍了React Router v4 重定向无法重定向的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

onEnter 替换为 render 我更改了代码以匹配路由器 v4 规范.重点是防止 /signup 页面在登录时显示.我的代码中缺少什么?

从'react'导入React;从 'react-dom' 导入 ReactDOM;从'流星/流星'导入{流星};从react-router-dom"导入 {BrowserRouter, Route, Redirect, Switch};从历史"中导入浏览器历史;从流星/跟踪器"导入 {Tracker};从'../imports/ui/Signup'导入注册;从'../imports/ui/MyLink'导入MyLink;从 '../imports/ui/NotFound' 导入 NotFound;从'../imports/ui/Login'导入登录;const history = browserHistory.createBrowserHistory();const unauthenticatedPages = ['/', '/signup'];const athenticatedPages = ['/mylink'];const onEnterPublicPage = () =>{如果(流星.userId()){return <Redirect to="/mylink/"/>;}};const 路由 = (<BrowserRouter history={history}><开关><路由精确路径="/" component={Login} render={() =>onEnterPublicPage}/><Route path="/signup" component={Signup} render={() =>onEnterPublicPage}/><Route path="/login" component={Login}/><Route path="/mylink" component={MyLink}/><Route path="*" component={NotFound}/></开关></BrowserRouter>);Tracker.autorun(() => {const isAuthenticated = !!Meteor.userId();const pathname = history.location.pathname;const isUnathenticatedPage = unathenticatedPages.includes(pathname);const isAthenticatedPage = athenticatedPages.includes(pathname);if (isAuthenticated && isUnathenticatedPage) {history.push('/mylink');} else if (!isAuthenticated && isAthenticatedPage) {history.push('/');}});Meteor.startup(() => {ReactDOM.render(routes, document.getElementById('app'));});

解决方案

使用 React Router 4,您不再像那样使用 Browserhistory.相反,它包含在 BrowserRouter 中,就像您在文档中看到的 .

另外,我不确定这是否能解决正在发生的事情,但我制作了一个 App 组件并将我的路由放在那里.然后,在 v4 中,历史记录在 props 中.然后你可以运行你的逻辑并执行props.history.push(url).

编辑:这是我用来让它工作的代码:

从'react'导入React;从'./Header'导入标题;从 './bins/BinsList' 导入 BinsList;从 './bins/BinsMain' 导入 BinsMain;import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';const App = (props) =>{返回 (<路由器><div><标题/><开关><路由精确路径="/" component={BinsList}></Route><Route path="/bins/:binId" component={BinsMain}></Route></开关>

</路由器>);}导出默认应用程序;

我的标题是这样呈现的:

import React, { Component } from 'react';从'./Accounts'导入帐户;从'react-router-dom'导入{链接,重定向,withRouter}类头扩展组件{onBinClick(e){e.preventDefault();Meteor.call('bins.insert', (err, bin) => {const url = `/bins/${bin}`;this.props.history.push(url);});}使成为() {返回 (<nav className="nav navbar-default"><div className="navbar-header"><Link to="/" className="navbar-brand">MarkBin</Link>

<ul className="nav navbar-nav"><li><帐户/><li><a href="#" onClick={this.onBinClick.bind(this)}>创建 Bin</a></nav>);}}导出默认 withRouter(Header);

With onEnter replaced with render I changed my code to match the router v4 specs. The point was to prevent the /signup page from getting displayed when logged in.What do i miss in my code?

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 onEnterPublicPage = () => {
  if (Meteor.userId()) {
    return <Redirect to="/mylink/" />;
  }
};

const routes = (
  <BrowserRouter history={history}>
    <Switch>
      <Route exact path="/" component={Login} render={() => onEnterPublicPage} />
      <Route path="/signup" component={Signup} render={() => onEnterPublicPage} />
      <Route path="/login" component={Login} />
      <Route path="/mylink" component={MyLink} />
      <Route path="*" component={NotFound} />
    </Switch>
  </BrowserRouter>
);

Tracker.autorun(() => {
  const isAuthenticated = !!Meteor.userId();    
  const pathname = history.location.pathname;

  const isUnathenticatedPage = unathenticatedPages.includes(pathname);
  const isAthenticatedPage = athenticatedPages.includes(pathname);

  if (isAuthenticated && isUnathenticatedPage) {
    history.push('/mylink');
  } else if (!isAuthenticated && isAthenticatedPage) {
    history.push('/');
  }
});

Meteor.startup(() => {
  ReactDOM.render(routes, document.getElementById('app'));
});

解决方案

With React Router 4, you no longer use Browserhistory like that. Instead, it is included in the BrowserRouter, like you see in the documentation.

Also, I am not sure if this will solve what's going on, but I make an App component and I put my routing in there. Then, with v4, the history comes through in props. Then you can run your logic and do props.history.push(url).

Edit: Here is the code I have used to get this to work:

import React from 'react';
import Header from './Header';
import BinsList from './bins/BinsList';
import BinsMain from './bins/BinsMain';
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';

const App = (props) => {
  return (
    <Router>
      <div>
        <Header />
        <Switch>
          <Route exact path="/" component={BinsList}></Route>
          <Route path="/bins/:binId" component={BinsMain}></Route>
        </Switch>
      </div>
    </Router>
  );
}

export default App;

And my header is rendered like this:

import React, { Component } from 'react';
import Accounts from './Accounts';
import { Link, Redirect, withRouter } from 'react-router-dom'


class Header extends Component {
  onBinClick(e){
    e.preventDefault();
    Meteor.call('bins.insert', (err, bin) => {
      const url = `/bins/${bin}`;
      this.props.history.push(url);
    });
  }

  render() {
    return (
      <nav className="nav navbar-default">
        <div className="navbar-header">
          <Link to="/" className="navbar-brand">MarkBin</Link>
        </div>
        <ul className="nav navbar-nav">
          <li>
            <Accounts />
          </li>
          <li>
            <a href="#" onClick={this.onBinClick.bind(this)}>Create Bin</a>
          </li>
        </ul>
      </nav>
    );
  }
}

export default withRouter(Header);

这篇关于React Router v4 重定向无法重定向的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
其他开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆