简体   繁体   English

为什么不回来<Redirect to="/" />跑步?

[英]why isn't return <Redirect to="/" /> running?

How come the return is not running?为什么返回没有运行? Is it because it is nested in 2 if statement?是因为它嵌套在 2 个 if 语句中吗? I am trying to do in in React, where I am checking the custom claims from Firebase, and if the user is an admin, then it will be redirected to the admin home page.我正在尝试在 React 中进行,在那里我正在检查来自 Firebase 的自定义声明,如果用户是管理员,那么它将被重定向到管理员主页。 Thanks~!谢谢~!

export default function() {
  const classes = useStyles();
  const { currentUser } = useContext(AuthContext);


    if (currentUser != null) {
      currentUser.getIdTokenResult().then(idTokenResult => {
        if (idTokenResult.claims.adminRole) {
          return <Redirect to="/adminHome" />;
        }
      });
    }

   return ( ... )
}

<Redirect to="/adminHome" /> can work, but not in your case. <Redirect to="/adminHome" />可以工作,但不适用于您的情况。 Because getIdTokenResult is async operation, and the return in the end of your component will return the result before the async getIdTokenResult operation will be finished.因为getIdTokenResult是异步操作,在你的组件末尾return ,会在异步getIdTokenResult操作完成之前返回结果。 And when getIdTokenResult will complete, it's too late to return something.getIdTokenResult完成时,返回某些内容为时已晚。

To do a redirect, do next:要进行重定向,请执行以下操作:

  1. import history进口历史

    import {useHistory} from 'react-router-dom'从 'react-router-dom' 导入 {useHistory}

  2. Use hook in component在组件中使用钩子

    const history = useHistory() const 历史 = useHistory()

And replace your code:并替换您的代码:

return <Redirect to="/adminHome" />;

to next:接下来:

history.push('/adminHome')

currently, your condition is not passing through.目前,你的情况没有通过。 Just modify an if statement.只需修改一个if语句。

if (idTokenResult.claims && idTokenResult.claims.adminRole) {
          return <Redirect to="/adminHome" />;
 }

If idTokenResult.claims.adminRole exists in an initial render the you can also try this.props.history.push("/adminHome") return null;如果idTokenResult.claims.adminRole存在于初始渲染中,您也可以尝试this.props.history.push("/adminHome") return null; . .

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

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