简体   繁体   English

为什么我的 React 应用登录后没有重定向到主页?

[英]Why isn't my react app redirecting to home after login?

I'm using react-router-dom to help handle routing but when I try to switch to the "/" route (my home page) after the user's auth state changes, it does not trigger the redirect.我正在使用react-router-dom来帮助处理路由,但是当我在用户的身份验证状态更改后尝试切换到“/”路由(我的主页)时,它不会触发重定向。 Routes work otherwise throughout the app (via Links).路线在整个应用程序中以其他方式工作(通过链接)。 The app is properly reflecting the user state throughout, just not redirecting.该应用程序始终正确反映用户状态,只是没有重定向。

My SignUp component is a class not functional component so I can't use hooks such as useHistory .我的 SignUp 组件是一个类不是功能组件,所以我不能使用像useHistory这样的useHistory

Here's my App.tsx:这是我的 App.tsx:

componentDidMount() {
    auth.onAuthStateChanged((user) => {
      this.setState({ currentUser: user }, () => {
        console.log("this is running") 
        // up to here is in fact being called when there is a successful sign in
        return <Redirect to="/" />;
      });
    });
  }


render() {
    return (
      <div>
        <Header currentUser={this.state.currentUser} /> 
        <Switch>
          <Route path="/" exact={true}>
            <Home currentUser={this.state.currentUser} key={`home`} />
          </Route>
          <Route
            exact={true}
            path="/sign-up"
            component={SignUp}
            key={`sign-up`}
          />
        </Switch>
      </div>
    );
  }
}

try to use this:尝试使用这个:

<Redirect
  to={{
     pathname: "/",
     state: { from: location }
  }}
/>

I'm more into functional components, but you're returning a tag on auth change, right?我更喜欢功能组件,但是您在身份验证更改时返回一个标签,对吗? Is this doing anything?这是在做什么吗? I think the <Redirect> tag only works in a <Router> after the route has been triggered.我认为<Redirect>标记仅在触发路由后在<Router>

Maybe you can find something here: How to push to History in React Router v4?也许你可以在这里找到一些东西: 如何在 React Router v4 中推送到历史记录?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM