我有一个上下文(AuthContext),可以让我知道用户是否已通过身份验证。我还创建了一条受保护的路由,如果用户通过了身份验证,则可以登录DashBoard,否则将重定向到登录。但是,我在将这两个连接在一起时遇到问题。
ProtectedRoute.js
import React from 'react';
import { Route, Redirect } from 'react-router-dom';
import { AuthContext } from './AuthContext';
const ProtectedRoute = ({ component: Component, ...rest }) => {
return (
<AuthContext.Consumer>
{(context) => {
const { isAuthenticated } = this.context;
return (
<Route
{...rest}
render={(props) => {
const { isAuthenticated } = this.context; //getting an error here
if (isAuthenticated) {
return <Component {...props} />;
} else {
return (
<Redirect
to={{
pathname: '/',
state: {
from: props.location,
},
}}
/>
);
}
}}
/>
);
}}
</AuthContext.Consumer>
);
};
export default ProtectedRoute;
AuthContext.js
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;
编辑后的代码(出现错误,指出渲染不是函数)
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
答案 0 :(得分:0)
提供给上下文使用者函数的参数是相应提供者中的value
道具。
return (
<AuthContext.Consumer>
{(context) => (
<Route
{...rest}
render={(props) => {
const { isAuthenticated } = context; // no `this`
// ...
}}
/>
)}
</AuthContext.Consumer>
);
我注意到您的原始代码中存在一些语法错误:
return
,则需要将使用者函数的主体括在括号中。