reactjs - 当 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 }
}} />
))
)} />
)
解决方案
该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>
}
推荐阅读
- jquery - 如何在动态构建下拉列表时自动选择它
- r - 如何在ggplot2中的时间线上绘制总共多行
- javascript - 对 JS 中的所有 Class 实例执行方法
- gnuplot - gnuplot 矩阵数据块图像
- python - 使用带有字符串数据的附加数据框时出错
- javascript - 在使用 JIC 库上传到服务器之前从客户端压缩多个图像
- php - 如何创建可以在其他功能中访问的全局服务器连接?
- android - 是否有在 NativeScript Angular 中选择文件的本地解决方案?
- blazor - 如何在 Blazor 中制作 Portal 组件?
- postgresql - 子查询问题 - 需要获得总和的平均值