簡體   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