【问题标题】:Get a wrong state in react-router在 react-router 中获取错误状态
【发布时间】:2023-03-29 18:03:01
【问题描述】:

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

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

但结果是假的。

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

谢谢!

【问题讨论】:

    标签: reactjs redux react-router


    【解决方案1】:

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

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

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

    【讨论】:

      猜你喜欢
      • 2016-04-24
      • 1970-01-01
      • 2016-02-04
      • 2022-12-03
      • 2021-12-01
      • 2019-10-19
      • 2019-08-23
      • 1970-01-01
      • 2020-07-09
      相关资源
      最近更新 更多