我试图查看用户是否已通过身份验证,然后使用ProtectedRoute将其发送到其他组件或将其重定向到登录。但是,我收到一个错误消息,指出render不是函数,无法使其运行。
受保护的路线
import React from 'react'
import { Route, Redirect } from 'react-router-dom'
import { AuthContext } from './AuthContext'
const ProtectedRoute = ({component: Component, ...rest}) => {
return (
<AuthContext.Consumer>
{({context}) => (
<Route
{...rest}
render={(props) => {
const {isAuthenticated} = context;
if(isAuthenticated) {
return <Component {...props} />;
} else {
return (
<Redirect
to={{
pathname: "/",
state: {
from: props.location
}
}}
/>
);
}
}}
/>
)};
</AuthContext.Consumer>
)
}
export default ProtectedRoute
AuthContext
import React, { Component, createContext} from 'react';
export const AuthContext = createContext();
class AuthContextProvider extends Component {
state = {
isAuthenticated: false
}
toggleAuth = () => {
this.setState({ isAuthenticated: !this.state.isAuthenticated})
}
render() {
return(
<AuthContext.Provider value={{...this.state, toggleAuth: this.toggleAuth}}>
{this.props.children}
</AuthContext.Provider>
)
}
}
export default AuthContextProvider;