【发布时间】:2018-12-01 08:08:00
【问题描述】:
我必须为我的应用配置路由。我正在本地系统上执行此操作。
我使用的包是"react-router": "^4.3.1"、"react-router-dom": "^4.3.1"、"history": "^4.7.2" 和"connected-react-router": "^4.3.0"。
我希望用户在导航到http://localhost:xxxx 时被重定向到http://localhost:xxxx/login。在 prod 的实际情况下,应从 window.location.pathname 中选择 baseUrl,然后将用户重定向到登录。
它没有解决下面代码中的目的。输入http://localhost:3000 后,新路径名http://localhost:3000/login 会在url 栏中可见,但不会加载登录页面。我看到的只是一个空白页。
但是,在下面的代码中,如果我在 History.js 中 return / 并从 Routes.js 中删除第二条路由,登录页面会成功加载。
History.js
import createHistory from 'history/createBrowserHistory';
function checkUrl() {
let baseUrl = window.location.pathname;
window.localStorage.setItem('baseUrl', baseUrl);
return `${baseUrl}`
}
const history = createHistory({
basename: checkUrl(),
});
export default history;
Routes.js
import React from 'react';
import { Route, Switch, Redirect } from 'react-router-dom';
import Login from '../Pages/Login/Login';
const Routes = () => (
<Switch>
<Route exact path="/login" component={Login} />
<Route
exact
path="/"
render={() => (
<Redirect to="/login" />
)}
/>
</Switch>
);
export default Routes;
商店
import { connectRouter, routerMiddleware } from 'connected-react-router/immutable';
import history from '../history/history';
const routeMiddleware = routerMiddleware(history);
//I have applied the middleware and configured rest of the store, here only exposed relevant information that I am using `connected-react-router`
我遇到了很多文章来解决这个问题,尝试了很多 P&C。但我无法理解这一点。
【问题讨论】:
-
检查你的登录组件,如果有东西(比如 redux)没有阻止更新。您也可以尝试切换路线顺序并将“/”路线放在第一位。我正在以类似的方式使用它并且它正在工作
标签: javascript reactjs react-router