Redux路由器pushState函数不会触发URL更改

时间:2016-10-14 21:39:41

标签: redux-router

我按照示例here尝试创建一个基本的身份验证区域 对于我的应用程序,这是我原则上非常喜欢的解决方案。这是我的index.js

const store = createStore(reducer);

ReactDOM.render(
  <Provider store={store}>
    <Router history={hashHistory}>
        <Route path="/" component={App}>
        <IndexRedirect to="authenticated" />
          <Route path="setup" component={SetupJourney} >
            <Route path="details" component={Details}/>
            <Route path="account" component={AccountType}/>
          </Route>
          <Route path="authenticated" component={requireAuthentication(secretPage)} />
      </Route>
    </Router>
  </Provider>,
  document.getElementById('root')
);

然后在我的AuthenticatedComponent高阶组件处理重定向:

export function requireAuthentication(Component) {

class AuthenticatedComponent extends React.Component {

    componentWillMount() {
        this.checkAuth();
    }

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

    checkAuth() {
        if (!this.props.isAuthenticated) {
            this.props.dispatch(pushState(null, '/setup/details', ''));
        }
    }

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

    }
}

const mapStateToProps = (state) => ({
    isAuthenticated: state.get('user').get('isAuthenticated')
});

return connect(mapStateToProps)(AuthenticatedComponent);

}

我已经玩了好几年了,我无法让组件重定向。在Redux开发工具中,我可以看到@@reduxReactRouter/historyAPI操作已触发,但URL没有更改。所有相关的道具/国家等似乎也都到位了......有没有我错过的东西?

由于

1 个答案:

答案 0 :(得分:0)

对于遇到这种情况的人,我最终解决了这个问题,并且存在一些问题。首先,pushState仅用于browserHistory,所以我需要从hashHistory切换。

此后pushState仍无法正常工作。当中间件以错误的顺序指定时,这可以apparently happen。我重新构建了我的index.js以遵循Redux的real world example中的模式,一切都最终奏效。

关键位是我现在有一个store.js文件,如下所示:

import { createStore, applyMiddleware, combineReducers, compose } from 'redux';
import { routerReducer, routerMiddleware} from 'react-router-redux';
import { browserHistory } from 'react-router';
import reducer, { INITIAL_STATE } from '../reducers/reducer';

const rootReducer = combineReducers({reducer, routing: routerReducer});
const composeEnhancers =
process.env.NODE_ENV !== 'production' &&
typeof window === 'object' &&
window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ ?
  window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__({
  }) : compose;

const enhancer = composeEnhancers(
  applyMiddleware(routerMiddleware(browserHistory))
);

const initialState = {'reducer': INITIAL_STATE};

export default function configureStore() {
  return createStore(rootReducer, initialState, enhancer);
}