首页 > 解决方案 > 当 isAuth 来自回调时创建私有路由

问题描述

我正在使用反应路由器私有路由系统。我正在检查身份验证,方法是从 localstorage 获取 jwt并在axios promise中对服务器进行交叉检查。

然而,私有路由似乎并不等待回调返回。我做的认证错了吗?或者有没有办法解决这个问题?

我的 axios 承诺检查身份验证。

const checkAuth = (cb) => {
    let token = localStorage.getItem("jwtToken");
    // console.log(token);
    if (token) {
        axios.defaults.headers.common["Authorization"] = token;
        axios
            .get("api/admin/auth/profile")
            .then(res => {
                localStorage.setItem("admin", res.data.admin);
                cb(null, res.data);
            })
            .catch(err => {
                showErr(err, cb);
            });
    } else {
        cb("Not authenticated", null);
    }
}

私人路线设置。

const PrivateRoute = ({ component: Component, ...rest, checkAuth }) => 
(
    <Route {...rest} render={(props) => (
        checkAuth((isAuthenticated) => (
            isAuthenticated === true
            ? <Component {...props} />
            : <Redirect to={{
              pathname: '/login',
              state: { from: props.location }
            }} />
        ))
    )} />
)

标签: reactjsauthenticationcallbackaccess-tokenreact-router-v4

解决方案


checkAuth方法不返回任何内容。渲染函数应该返回一个组件。我建议像这样创建一个有状态的 CheckAuth 组件。

class CheckAuth extends React.Component {
  state = {}

  componentDidMount () {
    this.props.checkAuth(isAuthenticated => {
      this.setState({isAuthenticated})
    })
  }

  render () {
     return this.props.children({loading, isAuthenticated})
  }
}

const PrivateRoute = ({ component: Component, ...rest, checkAuth }) => 
(
    <Route {...rest} render={(props) => 
      <CheckAuth {...props} checkAuth={checkAuth}>
       {({isAuthenticated}) => (
         isAuthenticated === true
         ? <Component {...props} />
         : <Redirect to={{
           pathname: '/login',
           state: { from: props.location }
        )}
      </CheckAuth>
    )}</Route>

} 

推荐阅读