在react-router中获取错误的状态

时间:2016-07-05 17:24:42

标签: reactjs redux react-router

所以我有一个这样的路由器:

const Routes = (props) => {
  const { store } = props;
  const { loggedIn } = props;
  const checkAuth = (nextState, replace) => {
    auth.checkAuth(nextState, replace, loggedIn);
  };
  return (
    <Provider store={store}>
      <Router history={browserHistory}>
        <Route component={App}>
          <Route path="/" component={HomePage} />
          <Route path="login" component={LoginPage} />
          <Route onEnter={checkAuth}>
            <Route path="about" component={AboutPage} />
            <Route path="help" component={HelpPage} />
            <Route path="help/new" component={HelpForm} />
          </Route>
        </Route>
      </Router>
    </Provider>
  );
};

Routes.propTypes = {
  loggedIn: PropTypes.bool.isRequired,
  store: PropTypes.object.isRequired,
};

function mapStateToProps(state) {
  return {
    loggedIn: state.user.loggedIn,
  };
}

export default connect(mapStateToProps)(Routes);

请注意我有道具: const { loggedIn } = props;

现在,每次调度动作时,我都会在redux调试器中看到状态已经改变。但是,在我单击checkAuth中不允许的链接后,我收到失败并将其重定向回登录页面。

我把console.log放在这里:

const checkAuth = (nextState, replace) => {
    console.log("from checkAuth: " + loggedIn);
    auth.checkAuth(nextState, replace, loggedIn);
  };

但结果是错误的。

我的问题是,为什么路线中的loggedIn没有更新?

谢谢!

1 个答案:

答案 0 :(得分:0)

我终于删除了我的连接,因为它不适合用于路由器。 我也使用store.getState()而不是使用道具,它可以工作。

const checkAuth = (nextState, replace) => {
    const { user } = store.getState();
    auth.checkAuth(nextState, replace, user.loggedIn);
  };

我认为我的答案并不完美。因此,如果有人有更好的答案或方式,请发布答案:)