使用API​​身份验证进行专用路由验证

时间:2020-05-03 09:32:36

标签: reactjs

我是新来的反应者,我一直在尝试为管理页面建立私有路线。

对于我的路由器,这是我的代码:

<React.Fragment>
  <Switch>
    <Route path='/' component={Home} exact>
      <Home />
    </Route>
    <Route path='/data' component={Data}>
      <Data />
    </Route>
    <ProtectedRoute path='/admin' component={Admin} />
  </Switch>
</React.Fragment>

然后对于我的ProtectedRoute组件,这就是我所拥有的:

if (Authenticated() === 200) {
  return <Route path={props.path} component={props.component} />;
} else {
  return <Redirect to='/' />;
}

然后对于Authenticated函数,我有:

function Authenticated() {
  const [auth, setAuth] = useState('');

  axios.get('/users').then((res) => {
    setAuth(res.status);
  });

  return auth;
}

我的问题是react会以空字符串的形式返回auth,然后返回另一个为200的字符串。ProtectedRoute中的条件不是在等待auth的最终值,因此它总是转到else语句。

1 个答案:

答案 0 :(得分:0)

问题似乎出在您的Autheticated函数返回单个调用返回多个结果的情况下。

我建议的一种快速修复方法是检查故障,而不是else

if (Authenticated() === 200) {
  return <Route path={props.path} component={props.component} />
}

if (Authenticated() === 401) {
  return <Redirect to='/' />
}

这可以避免<Redirect to='/' />,直到您确定身份验证失败

对于两次调用,如果您通过Authenticated函数发布代码,则可能会得到帮助以防止其返回空字符串。