Javascript 如何在未登录的情况下访问主组件?

Javascript 如何在未登录的情况下访问主组件?,javascript,reactjs,Javascript,Reactjs,在React项目中,我创建了某些组件,这些组件只有在登录时才具有访问权限,否则将重定向到登录页面。虽然我被告知要做一些更改,但即使没有登录,用户也应该可以访问主页。要访问其他组件,用户必须具有令牌。参考以下代码 export const UserContext = createContext(); const Routing = () => { const history = useHistory() const { state, dispatch } = useContext(Us

在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;
export const UserContext=createContext();
常量路由=()=>{
const history=useHistory()
const{state,dispatch}=useContext(UserContext)
const[value,setValue]=useState(null)
const user=sessionStorage.getItem('token')
useffect(()=>{
如果(用户){
分派({type:“USER”,payload:USER})
}否则{
history.push(“/login”)
}}, [])
返回(
{/*即使未登录或具有令牌,也向用户授予访问权限*/}
{/*我不允许用户访问此组件,除非令牌可用*/}
)
}
常量应用=()=>{
const[state,dispatch]=useReducer(reducer,initialState)
返回(
)
}
导出默认应用程序;

那么,什么可能是最好的解决方案呢?即使未登录也可以访问主页,但是,当尝试访问其他组件(如VideoCall)时,请将用户重定向到登录页。

也许类似的方法会有所帮助-您自己的路由器组件,这将检查用户是否经过身份验证,并决定是否允许他进入组件。如果您希望呈现主组件,只需使其呈现;如果用户未登录,则不希望呈现的组件,只需在该组件(或您自己的路由器组件)中添加检查,以确定用户是否经过身份验证


顺便说一句,每次渲染时,
用户
常量都会被分配sessionstorage.getItem()值。。。每一次渲染。如果您希望它只发生一次,或者只在特定变量更改时发生-您应该完全使用
usemo
const user=usemo(()=>sessionStorage.getItem(),[])
)()(

谢谢您的回复,您能建议对我的代码进行任何更改吗?