在React项目中,我创建了某些组件,这些组件只有在登录时才能访问,否则将重定向到登录页面。虽然我被告知要做一些更改,但用户应该有权访问主页,即使没有登录。要访问其他组件,用户必须具有令牌。请参阅以下代码以供参考
export const UserContext = createContext();
const Routing = () => {
const history = useHistory()
const { state, dispatch } = useContext(UserContext)
const [value, setValue] = useState(null)
const user = sessionStorage.getItem('token')
useEffect(() => {
if(user) {
dispatch({ type: "USER", payload: user })
} else {
history.push('/login')
}}, [])
return (
<>
<Router>
<Switch>
{/* Give access to user even though not logged in or has token */}
<Route exact path="/" component="Home" />
{/* I won't let user access this Component, unless token is available */}
<Route exact path="/videoCall" component="VideoCall" />
</Switch>
</Router>
</>
)
}
const App = () => {
const [state, dispatch] = useReducer(reducer, initialState)
return (
<UserContext.Provider value={{state, dispatch}}>
<Router>
<Switch>
<Route exact path="/login" component={LoginPage} />
<Routing />
</Switch>
</Router>
</UserContext.Provider>
)
}
export default App;那么,什么可能是最好的解决方案,即使没有登录,也可以访问主页,但是,当用户尝试访问其他组件(如VideoCall )时,将用户重定向到登录页面。
发布于 2021-05-07 21:08:24
也许像这样的东西会有所帮助--你自己的一个路由器组件,它将检查用户是否通过了身份验证,并决定是否让他进入组件。如果你想渲染Home组件,只需要渲染它,如果用户没有登录,你不想渲染的组件,只需在组件(或您自己的路由器组件)中添加检查用户是否通过身份验证……
顺便说一句,每次渲染时,user常量都会被赋予sessionstorage.getItem()值...每次渲染。如果您希望它只发生一次,或者只在特定变量发生更改时发生-您应该完全使用useMemo (const user = useMemo(()=>sessionStorage.getItem(), [])) (https://reactjs.org/docs/hooks-reference.html#usememo)
https://stackoverflow.com/questions/67432395
复制相似问题