【问题标题】:Creating private route when isAuth comes from a callback当 isAuth 来自回调时创建私有路由
【发布时间】:2018-10-25 15:58:28
【问题描述】:

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

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

我的 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 }
            }} />
        ))
    )} />
)

【问题讨论】:

    标签: reactjs authentication callback access-token react-router-v4


    【解决方案1】:

    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>
    
    } 
    

    【讨论】:

      猜你喜欢
      • 2020-11-17
      • 1970-01-01
      • 2022-01-17
      • 2021-06-18
      • 2022-11-05
      • 2023-02-08
      • 1970-01-01
      • 2021-10-03
      • 2016-08-28
      相关资源
      最近更新 更多