[英]Protected Route and React Context
我有一個上下文(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
提供給上下文消費者 function 的參數是相應提供者中的value
prop。
return (
<AuthContext.Consumer>
{(context) => (
<Route
{...rest}
render={(props) => {
const { isAuthenticated } = context; // no `this`
// ...
}}
/>
)}
</AuthContext.Consumer>
);
我注意到在您的原始代碼中存在一些語法錯誤:
return
,則需要將消費者 function 的主體括在大括號中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.