React-router-redux推送操作无效

时间:2018-02-14 09:07:12

标签: reactjs react-router react-router-redux

我正在尝试在身份验证成功后导航到主页面,我正在使用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并尝试这样做,有人可以告诉我我做错了什么吗?

1 个答案:

答案 0 :(得分: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。