0

我已经按照这里的示例尝试为我的应用程序创建一个基本的身份验证区域,这是我原则上非常喜欢的解决方案。这是我的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 没有更改。所有相关的道具/状态等似乎也都到位了……我错过了什么吗?

谢谢

4

1 回答 1

0

对于遇到此问题的任何人,我最终都解决了这个问题,并且存在一些问题。首先,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);
}
于 2016-10-18T08:09:20.580 回答