【问题标题】:React hide header component for some routes反应隐藏某些路由的标题组件
【发布时间】:2021-04-10 07:53:43
【问题描述】:

我有 3 个组件,WelcomePage、RegisterPage、HeaderLogOut。

我希望当用户在 RegisterPage 上时隐藏 HeaderLogOut 组件。在 RegisterPage 中,用户可以点击应用的 logo 图标,将被重定向到 WelcomePage,它会有 HeaderLogOut 组件,可以将用户重定向回 RegisterPage。

我看到过类似的问题和文章,它们展示了这是如何完成的。但我的问题是,例如,当我在 WelcomePage 上并单击登录时,RegisterPage 页面有 HeaderLogOut 并且只有在我刷新页面后它才会消失。与 WelcomePage 相同,当我在 RegistrationPage 并单击应用程序的徽标时,它会将我重定向到 WelcomePage,并且我没有 HeaderLogOut,只有在刷新后才会出现。我进行了多次尝试,但我不明白为什么它不会在没有硬刷新的情况下立即渲染组件。

对于路由,我使用来自react-router-dom 钩子的useHistory

const history = useHistory();

onClick={() => {
  history.push("/welcome");
}}

我在 App.js 中有什么

return (
  <React.Fragment>
      {/* {history.location.pathname === "/register" ? null : currentUser ? (
        <HeaderLogIn />
      ) : (
        <HeaderLogOut />
      )} */}
      {location.pathname !== "/register" && !currentUser && <HeaderLogOut />}
      {location.pathname !== "/register" && currentUser && <HeaderLogIn />}
    <Switch>
      <Route exact path="/register" component={RegistrationPage} />
      <Route
        exact
        path="/welcome"
        render={() => (currentUser ? <Redirect to="/" /> : <WelcomePage />)}
      />
      ... other routes
    </Switch>
  </React.Fragment>
);

const mapStateToProps = createStructuredSelector({
  currentUser: selectCurrentUser,
});
const mapDispatchToProps = (dispatch) => ({
  setCurrentUser: (user) => dispatch(setCurrentUser(user)),
});
export default connect(mapStateToProps, mapDispatchToProps)(App);

我像这样使用我的用户减速器来测试是否登录用户。

const user = {
  username: "bvcbvc",
  email: "fdfsdfs",
};

const INITIAL_STATE = {
  currentUser: null, // user, if logged in
};

【问题讨论】:

  • 我看不出currentUser 道具是如何与任何路由转换相关联的,但是在转换到新路由并重新加载页面后currentUser 发生了什么变化?
  • @DrewReese 我正在使用 redux-logger,我看到它的值为 null 表示用户未登录。我认为问题可能是在路由转换后组件不重新渲染

标签: reactjs react-router


【解决方案1】:

我认为问题在于 App 组件未重新渲染,因此 locationcurrentUser 未重新评估。

一种解决方案可能是有条件地在Switch 之外的通用路由上呈现标头组件,以便Route 可以传递更新的location 值以进行条件测试。

return (
  <React.Fragment>
    <Route
      render={({ location }) =>
        location.pathname !== "/register" && currentUser ? (
          <HeaderLogIn />
        ) : (
          <HeaderLogOut />
        )
      }
    />
    <Switch>
      <Route exact path="/register" component={RegistrationPage} />
      <Route
        exact
        path="/welcome"
        render={() => (currentUser ? <Redirect to="/" /> : <WelcomePage />)}
      />
      ... other routes
    </Switch>
  </React.Fragment>
);

【讨论】:

    猜你喜欢
    • 2018-07-29
    • 2021-11-26
    • 1970-01-01
    • 2019-04-05
    • 1970-01-01
    • 2022-08-02
    • 1970-01-01
    • 1970-01-01
    • 2021-03-29
    相关资源
    最近更新 更多