2016-10-14 27 views
0

我按照示例here嘗試爲我的應用創建基本認證區域 ,這是我原則上非常喜歡的解決方案。這是我index.jsRedux路由器pushState功能不觸發URL更改

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不會更改。所有相關的道具/狀態等似乎都已到位......是否有我錯過的東西?

感謝

回答

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); 
}