[英]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.