Reactjs 为什么不是';登录后我的react应用程序不会重定向到主页吗?

Reactjs 为什么不是';登录后我的react应用程序不会重定向到主页吗?,reactjs,react-router,react-router-dom,Reactjs,React Router,React Router Dom,我正在使用react router dom来帮助处理路由,但当我尝试在用户的身份验证状态更改后切换到“/”路由(我的主页)时,它不会触发重定向。路由在整个应用程序中起作用(通过链接)。应用程序始终正确地反映用户状态,只是没有重定向 我的注册组件是一个类而不是功能组件,所以我不能使用钩子,比如useHistory 这是我的App.tsx: componentDidMount() { auth.onAuthStateChanged((user) => { this.setS

我正在使用
react router dom
来帮助处理路由,但当我尝试在用户的身份验证状态更改后切换到“/”路由(我的主页)时,它不会触发重定向。路由在整个应用程序中起作用(通过链接)。应用程序始终正确地反映用户状态,只是没有重定向

我的注册组件是一个类而不是功能组件,所以我不能使用钩子,比如
useHistory

这是我的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>
    );
  }
}
componentDidMount(){
auth.onAuthStateChanged((用户)=>{
this.setState({currentUser:user},()=>{
log(“这正在运行”)
//事实上,当成功登录时,将调用到此处
返回;
});
});
}
render(){
返回(
);
}
}
尝试使用以下方法:

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

我更喜欢功能组件,但您在验证更改时返回了一个标记,对吗? 这有什么用吗? 我认为
标签只在触发路线后在
中起作用


也许你可以在这里找到一些东西:

根据“地点”,我想这个案例应该是“注册”?我用location=“sign up”尝试了您的建议,但不幸的是得到了相同的结果。您是否尝试离开location?不注册也可以尝试
如果由于
意外使用“location”而将其保留为location,则类型脚本将不会编译,没有限制的全局变量。我尝试了
,但也不起作用。您不能在setState中使用组件作为回报。您可以尝试使用push
props.history.push(“/”)
。组件已始终具有历史记录。所以你不需要在ts中声明这个类型。