React Redux路由仅刷新,登录后需重定向至主组件问题求助
解决React Redux登录后路由仅刷新不跳转的问题
我之前也碰到过一模一样的情况,大概率是路由和Redux的联动配置没做对,或者react-router-redux的使用方式不符合新版本要求,给你几个实用的排查和解决方向:
1. 先确认依赖包与核心配置是否正确
如果你的React Router是v4及以上版本,旧版的react-router-redux已经不再维护,官方推荐用connected-react-router来实现路由与Redux的联动。
首先安装正确的依赖:
npm install connected-react-router react-router-dom redux-thunk
然后在Redux Store的配置文件(比如store.js)里,把路由历史和Store绑定:
import { createBrowserHistory } from 'history'; import { applyMiddleware, compose, createStore } from 'redux'; import { connectRouter, routerMiddleware } from 'connected-react-router'; import rootReducer from './reducers'; // 创建全局路由历史对象 export const history = createBrowserHistory(); export default function configureStore(preloadedState) { const store = createStore( // 将路由状态合并进Redux的根Reducer connectRouter(history)(rootReducer), preloadedState, compose( applyMiddleware( // 加入路由中间件,让dispatch可以处理路由相关的action routerMiddleware(history), // 你的其他中间件比如redux-thunk ), ), ); return store; }
最后在根组件里,用ConnectedRouter替代普通的BrowserRouter包裹路由:
import { ConnectedRouter } from 'connected-react-router'; import { history } from './store'; import Routes from './Routes'; function App() { return ( <ConnectedRouter history={history}> <Routes /> </ConnectedRouter> ); }
2. 修改登录Action的写法
确保你导入的是connected-react-router提供的push方法,而不是旧版的:
import axios from 'axios'; import { push } from 'connected-react-router'; // 这里替换成正确的包 import { API_URL } from '../utils/apiUrl'; export const loginUser = creds => { return dispatch => { dispatch(loginRequest(creds)); axios({ method: "post", url: API_URL + "/auth_token", data: { auth: creds } }).then(res => { // 现在这个push应该能正确触发路由跳转,而不是只刷新 dispatch(push('/home')); // 别忘了处理登录成功的其他逻辑,比如把token存入Store dispatch(loginSuccess(res.data.token)); }).catch(err => { dispatch(loginFailure(err.response.data)); }); }; };
3. 排查是否有阻止跳转的额外逻辑
有时候组件里的shouldComponentUpdate钩子、或者React Strict Mode可能会干扰路由跳转,你可以暂时关闭Strict Mode测试一下;另外也检查下是否有自定义的路由守卫逻辑,误阻止了页面跳转。
4. 临时调试方案:直接用history对象跳转
如果上面的配置还是有问题,你可以直接用全局的history对象来跳转作为临时方案:
import { history } from '../store'; // 导入我们之前创建的全局history // 在登录成功的回调里: history.push('/home');
这种方式虽然不如Redux Action规范,但能快速验证是否是路由配置的问题。
内容的提问来源于stack exchange,提问作者Claim
相关产品推荐
相关产品推荐

