首页 > 解决方案 > 如何在 react 中使用 history.push

问题描述

大家好,我创建了一个新操作来登录用户,如下所示:

import * as types from './actionTypes';
import sessionApi from '../api/SessionApi';
import auth from '../auth/authenticator';


export function loginSuccess() {
 return {type: types.LOG_IN_SUCCESS}
 }

export function loginUser(credentials) {
 return function(dispatch) {
 return sessionApi.login(credentials).then(response => {

  sessionStorage.setItem('token', response.token);
  dispatch(loginSuccess());
}).catch(error => {

  throw(error);
   });
  };
 }

 export function logOutUser() {
  auth.logOut();
  return {type: types.LOG_OUT}
 }

我为我的身份验证创建了一个会话缩减器,如下所示:

import * as types from '../actions/actionTypes';
import initialState from './initialState';



export default function sessionReducer(state = initialState.session, 
 action) {
  switch(action.type) {
   case types.LOG_IN_SUCCESS:
    // history.push('/restaurant')
    return !!sessionStorage.token
  default:
  return state;
   }
  }

登录成功后,我想使用 history.push 将我的用户重定向到另一个页面,但我不知道该怎么做?我尝试先导入

import createBrowserHistory from "history/createBrowserHistory"

然后像这样创建一个新的 const 历史:

export const history = createBrowserHistory({
forceRefresh: true
})

接着

history.push('/restaurant')

但在行动之后,将我从 /#home 重定向到 /restaurant/#home .... 而不是我的正确组件。对于我的主要视图,我有 2 个路由文件,如下所示:

const routes = [
 { path: '/', name: 'Home', component: Home },
 { path: '/login', name: 'Login', component: Login },
 { path: '/home', name: 'Landing', component: Landing },
 { path: '/dishes', exact: true, name: 'Detail', component: Dish },
 { path: '/dishes/detail', name: 'DishDetail', component: Detail },
 { path: '/checkout/registration', name: 'Restaurant', component: 
 Registration },
 ];

 export default routes;

和我所有的餐厅景观都是这样的:

const routes = [
{ path: '/restaurant', exact: true, name: 'Restaurant', component: 
RestrauntDashboard },
{ path: '/restaurant/dashboard', name: 'Restaurant Dashboard', 
component: Dashboard },
{ path: '/restaurant/profile', name: 'Restaurant Dashboard', component: 
Profile },
];

export default routes;

这是我的 app.js :

class App extends Component {
 render() {
  return (
      <HashRouter>
          <Switch>
              <Route path="/restaurant" name="Restaurant" component= . 
               {RestrauntDashboard} />
              <Route path="/" name="Home" component={Home} />
          </Switch>
      </HashRouter>
   );
 }
}

export default App;

所以最后我想在他登录后重定向用户在'/restaurant/路径中,通过使用history.push,谢谢你的帮助

标签: reactjsreact-routerreact-redux

解决方案


由于您使用的是 HashRouter,因此您可以使用historyfrom props 中提到的Programmatically Navigate using react-router

或者您需要使用createHashHistory而不是创建历史记录createBrowserHistory并将其传递给通用路由器组件,例如

import { Router } from 'react-router-dom';
export const history = createHashHistory();

class App extends Component {
 render() {
  return (
      <Router history={history}>
          <Switch>
              <Route path="/restaurant" name="Restaurant" component= . 
               {RestrauntDashboard} />
              <Route path="/" name="Home" component={Home} />
          </Switch>
      </HashRouter>
   );
 }
}

推荐阅读