Reactjs 当isAuth来自回调时创建专用路由

Reactjs 当isAuth来自回调时创建专用路由,reactjs,authentication,callback,access-token,react-router-v4,Reactjs,Authentication,Callback,Access Token,React Router V4,我正在使用react路由器专用路由系统。我正在检查身份验证,方法是从localstorage获取jwt,并在axios promise中对服务器进行交叉检查 然而,私有路由似乎并不等待回调返回。 我的身份验证有错吗?还是有办法解决这个问题 我的axios承诺检查身份验证 const checkAuth = (cb) => { let token = localStorage.getItem("jwtToken"); // console.log(token); if

我正在使用react路由器专用路由系统。我正在检查身份验证,方法是从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 }
            }} />
        ))
    )} />
)
const privaterout=({component:component,…rest,checkAuth})=>
(
(
checkAuth((已验证)=>(
isAuthenticated==真
? 
: 
))
)} />
)

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>

} 
类CheckAuth扩展了React.Component{
状态={}
组件安装(){
this.props.checkAuth(isAuthenticated=>{
this.setState({isAuthenticated})
})
}
渲染(){
返回此.props.children({loading,isAuthenticated})
}
}
const privaterout=({component:component,…rest,checkAuth})=>
(
{({isAuthenticated})=>(
isAuthenticated==真
? 
: