react-router-redux不会更改内容/视图

时间:2016-09-04 06:13:49

标签: reactjs react-router-redux

我将react-router-redux设置为example。但dispatch(push(url))不会更改内容/视图,也不会更改地址栏上的网址。即使从我的控制台,我可以看到使用我的给定地址成功调用了LOCATION_CHANGE和CALL_HISTORY_METHOD。在这种情况下,如果登录成功,则不会加载预期的redirect地址。

登录行动

export function loginUser(email, password, redirect="/dashboard") {
  return function(dispatch) {
    dispatch(loginUserRequest());
    return fetch(`http://localhost:3000/users/sign_in/`, {
      ...
    })
    .then(parseJSON)
    .then(response => {
      try {
        let decoded = jwtDecode(response.token);
        dispatch(loginUserSuccess(response.token));
        dispatch(push(redirect));
      } catch (e) {
        ...
      }
    })
  }
}

routes.js

import React from 'react';
import { Router, Route, browserHistory, IndexRoute } from 'react-router';
import { syncHistoryWithStore } from 'react-router-redux'
...
import store from '../store';

const history = syncHistoryWithStore(browserHistory, store)

let Routes = 
  <Router history={history}>
    <Route path='/' component={MainContainer}>
      <IndexRoute component={Home} />
      <Route path='/sign_in' component={SigninForm} />
      <Route path='dashboard' component={authenticateComponent(Dashboard)} />
    </Route>
  </Router>

export default Routes;

store.js

import { createStore, applyMiddleware, compose } from 'redux'
import thunkMiddleware from 'redux-thunk'
import createLogger from 'redux-logger'
import reducers from './reducers';

const createStoreWithMiddleware  = compose(
  applyMiddleware(
    thunkMiddleware,
    createLogger()
  )
)

const store = createStore(reducers, createStoreWithMiddleware);

export default store;

AuthenticateComponent.js

import React, { Component } from 'react';
import { connect } from 'react-redux';
import { push } from 'react-router-redux';

export function authenticateComponent(Component) {

  class AuthenticateComponent extends Component {

    componentWillMount () {
      this.checkAuth(this.props.isAuthenticated);
    }

    componentWillReceiveProps (nextProps) {
      this.checkAuth(nextProps.isAuthenticated);
    }

    checkAuth (isAuthenticated) {
      if (!isAuthenticated) {
        let redirectAfterLogin = this.props.location.pathname;
        this.props.dispatch(push(`/sign_in?next=${redirectAfterLogin}`));
      }
    }

    render () {
      return (
        <div>
          {this.props.isAuthenticated === true
            ? <Component {...this.props}/>
            : null
          }
        </div>
      )
    }
  }

  const mapStateToProps = (state) => ({
    token: state.auth.token,
    isAuthenticated: state.auth.isAuthenticated
  });

  return connect(mapStateToProps)(AuthenticateComponent);

}

我已将routing: routerReducer放入我的合并缩减器中。这可能是什么问题?

1 个答案:

答案 0 :(得分:1)

原来我需要同时应用routerMiddleware