[英]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>
有幾點要補充到問題中:
PrivateRoute
中確實發生了重定向(我通過將to
參數更改為另一個路由對此進行了測試,並且我在瀏覽器中看到了 URI 更改)。/sign_in
,它工作正常。 唯一的問題是僅當<Redirect>
執行此操作時。這是我以前嘗試過的嘗試;
PrivateRoute
withRouter
基於這個答案PrivateRoute
設置為pure
- 基於此答案react-router
而不是react-router-dom
導入Redirect
和withRouter
path-to-regexp@^2.4.0
Redirect
中使用push
- 基於此答案我目前正在使用react-router-dom@5.2.0
和react@^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-dom
從5.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.