React-router-redux推送操作不起作用

问题描述 投票:3回答:1

身份验证成功后,我试图导航至主页,我正在使用redux-saga进行API调用。下面是我的登录生成器函数:

 import * as Type from '../actions/types';
import { takeLatest, put, call } from 'redux-saga/effects';
import firebase from 'firebase';
import { push } from 'react-router-redux';


function* loginUser(action) {
    const auth = firebase.auth();

    try{
        console.log(action.user);
        const result = yield call([auth, auth.signInWithEmailAndPassword], action.user.email, action.user.password);
        console.log('login sucess');
        yield put({type: Type.AUTH_SUCCESSFULL, user: action.user, authMessage:'Login Success'});
        console.log('done');  //being logged
        yield put(push('/home')); /not being redirected to home. Even the browser url is not changing
        console.log('pushed'); //being logged
    }
    catch(error){
      console.log(error.message);
      yield put({type: Type.AUTH_FAILED, errorMessage: error.message});
    }
 }

我刚刚安装了react-router-redux并尝试执行此操作,有人可以告诉我我做错了什么吗?

reactjs react-router react-router-redux
1个回答
0
投票

我遇到了同样的问题,下面是我的解决方案。您添加的代码没有问题。您需要做一些额外的工作才能使它起作用。

Reducer.js

import { combineReducers } from 'redux';
import { connectRouter } from 'connected-react-router';
import { History } from 'history'

const redusers = {
  ...
}

const mainReducer = (history: History) => combineReducers({
  router: connectRouter(history),
  ...redusers
})

export default mainReducer;

Store.js

import { createStore, applyMiddleware } from 'redux';
import createSagaMiddleware from 'redux-saga';
import logger from 'redux-logger';
import { createBrowserHistory } from 'history'
import { routerMiddleware } from 'connected-react-router'

import mainReducer from './mainReducer';
import rootSaga from './rootSaga';

export const history = createBrowserHistory()

const configureStore = (preloadedState?: any) => {
  const sagaMiddleware = createSagaMiddleware();
  const store = createStore(
    mainReducer(history),
    preloadedState,
    applyMiddleware(routerMiddleware(history), logger, sagaMiddleware),
  );
  sagaMiddleware.run(rootSaga);
  return store;
};

export default configureStore;

index.js

import React, { Suspense } from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';

import App from './App';
import * as serviceWorker from './serviceWorker';
import configureStore, { history } from './store';

const store = configureStore();
const app = (
    <Provider store={store}>
        <App history={history} />
    </Provider>
);

App.js-仅在下面添加了必要的代码行

...
import { History } from 'history'
import { ConnectedRouter } from 'connected-react-router'
...

const {history} = props;
...

return(){
   ...
   <ConnectedRouter history={history}>
      {routes}
   </ConnectedRouter>
   ...
}

在您的应用上完成以上设置后,它将可以根据需要运行。

另一件事是,由于实现了自定义历史记录,我们不再在应用程序中使用BrowserHistory。

© www.soinside.com 2019 - 2024. All rights reserved.