当 isAuth 来自回调时创建私有路由
Creating private route when isAuth comes from a callback
我使用的是react router私有路由系统。我正在检查身份验证,方法是从 localstorage 获取 jwt 并在 axios promise.
中针对服务器进行交叉检查
然而,私有路由似乎并不等待回调到 return。
我做的身份验证错了吗?还是有办法解决这个问题?
我的 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
方法return 没什么。渲染函数应该 return 一个组件。我建议像这样创建一个有状态的 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>
}
我使用的是react router私有路由系统。我正在检查身份验证,方法是从 localstorage 获取 jwt 并在 axios promise.
中针对服务器进行交叉检查然而,私有路由似乎并不等待回调到 return。 我做的身份验证错了吗?还是有办法解决这个问题?
我的 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
方法return 没什么。渲染函数应该 return 一个组件。我建议像这样创建一个有状态的 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>
}