我必须为我的应用程序配置路由。我在我的本地系统上做这件事。我使用的包是"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
后,url栏中会显示一个新的路径名http://localhost:3000/login
,但不会加载登录页面。我看到的只是一页空白。
然而,在下面的代码中,如果我在History.js中return /
并从Routes.js中删除第二条路由,则登录页面加载成功。
历史.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.但是我无法理解这件事。
您的更新很可能被阻止了。请参阅:https://reacttraining.com/react-router/web/guides/redux-integration有趣的是,将连接组件的导出包装在"withRouter"中,以便添加路由道具,由于道具差异触发重新渲染
引用上面引用的链接:
"一般来说,React Router和Redux配合得很好。不过,偶尔应用程序可能会有一个组件在位置变化时不会更新(子路线或活动导航链接不会更新(。
如果:
该组件通过connect(((Comp(连接到redux。该组件不是"路由组件",这意味着它不是这样呈现的:问题是Redux实现了shouldComponentUpdate,如果它没有从路由器接收道具,就没有迹象表明任何事情发生了变化。这很容易解决。找到连接组件的位置,然后用Router将其封装起来。">
当我将App.js封装在withRouter
中时,它开始正常工作。