繁体   English   中英

React Router DOM - 重定向组件无法正确呈现路由

[英]React Router DOM - Redirect component does not render route properly

我意识到以前有人问过这个问题,请多多包涵,因为我还在学习这个。 而且我想我已经尝试了 SO 中的所有解决方案,但没有运气。

问题是:当PrivateRoute重定向到/sign_in时,它没有呈现预期的组件( SignInForm

我已经实现了PrivateRoute如下;

PrivateRoute.js

import React, { Component } from "react";
import PropTypes from "prop-types";
import { connect } from "react-redux";
import { Route, Redirect, withRouter } from "react-router-dom";

// Simplified and still can reproduce the issue;
class PrivateRoute extends Route {
  render () {
    return (<Redirect to="/sign_in" />);
  }
}

PrivateRoute.propTypes = {
  isAuthenticated: PropTypes.bool.isRequired,
};

const mapStateToProps = state => {
  return {
    isAuthenticated: !!state.user.token
  };
};

export default withRouter(connect(mapStateToProps)(PrivateRoute));

这就是我使用它的地方;

index.js

<div className="content position-relative">
    <div className="content-container font-nunito">
        <Switch>
            <Route path="/sign_in" component={SignInForm} />
            <Route exact path="/" component={LandingPage} />
            <PrivateRoute path="/trips" component={TestPage} />
        </Switch>
    </div>
</div>

有几点要补充到问题中:

  1. 我确认在PrivateRoute中确实发生了重定向(我通过将to参数更改为另一个路由对此进行了测试,并且我在浏览器中看到了 URI 更改)。
  2. 如果我 go 直接到/sign_in它工作正常 唯一的问题是仅当<Redirect>执行此操作时。
  3. 如果这无法解决,我最后的手段是粗暴地进行本机浏览器重定向。 但是,如果可能的话,我想避免这种情况。

这是我以前尝试过的尝试;

  1. 在我的PrivateRoute withRouter基于这个答案
  2. PrivateRoute设置为pure - 基于此答案
  3. 尝试从react-router而不是react-router-dom导入RedirectwithRouter
  4. 安装path-to-regexp@^2.4.0
  5. Redirect中使用push - 基于此答案

我目前正在使用react-router-dom@5.2.0react@^16.2.0

请帮助,任何建议表示赞赏。 让我知道我是否可以提供更多详细信息。

编辑:我发现了真正的问题,似乎所有路由都需要包装在BrowserRouter中。 所以这是我的最终解决方案;

<BrowserRouter>
    <div className="content position-relative">
        <div className="content-container font-nunito">
            <Switch>
                <Route path="/sign_in" component={SignInForm} />
                <Route exact path="/" component={LandingPage} />
                <PrivateRoute path="/trips" component={TestPage} />
            </Switch>
        </div>
    </div>
</BrowserRouter>

老的:

我通过将react-router-dom5.2.0降级到4.3.1解决了这个问题。

这似乎解决了这个问题的一些副作用

所以我最后的改变是;

package.json

- "react-router-dom": "^5.2.0",
+ "react-router-dom": "^4.3.1",

index.js (为了避免副作用)

<Switch>
    <Route exact path="/" component={props => <LandingPage {...props} />} />
    <Route path="/sign_in" component={props => <SignInForm {...props} />} />

    <PrivateRoute path="/trips" component={props => <TestPage {...props} />} />
</Switch>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM