簡體   English   中英

Redux路由器pushState函數不會觸發URL更改

[英]Redux router pushState function not triggering URL change

我按照此處的示例嘗試為我的應用創建一個基本的經過身份驗證的區域,這是我原則上非常喜歡的解決方案。 這是我的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不變。 所有相關的道具/狀態等等似乎也都到位了...我錯過了什么嗎?

謝謝

對於遇到此問題的任何人,我最終都解決了這個問題,並且存在一些問題。 首先,pushState僅用於browserHistory,因此我需要從hashHistory切換。

此后,pushState仍然不起作用。 如果以錯誤的順序指定了中間件, 顯然會發生這種情況 我重組了index.js以遵循Redux 真實示例中的模式,最終一切正常。

關鍵是我現在有一個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);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM