2

当我尝试读取数据时,除了我的 SwitchRouter.tsx 之外,它已成功登录到每个文件的控制台中,我不知道为什么。我要做的是获取 user(isLogin) 的值并基于该值有条件地渲染组件。(如果用户已登录,则用户可以访问 UserContact、UserPosts 和 AboutMe,如果用户未登录,则他只能访问 HomePage)

导航栏.tsx

function NavigationBar() {

    const { user } = useContext(LoginUserContext)

    console.log('nav bar', user)                      // working fine

    return (
        <div>
            <Router>
                <NavLinkRouter />
                <SwitchRouter />
            </Router>
        </div>
    )
}

export default NavigationBar
function SwitchRouter() {

    const { user } = useContext(LoginUserContext)

    console.log('switch route', user)                    // not displaying anything

    return (
        <Switch>
            <Route path="/" exact component={HomePage} />
            <Route path="/contacts" render={() => (user.isLogin ? <UserContact /> : <Redirect to="/" />)} />
            <Route path="/posts" render={() => (user.isLogin ? <UserPosts /> : <Redirect to="/" />)} />
            <Route path="/aboutme" render={() => (user.isLogin ? <AboutMe /> : <Redirect to="/" />)} />
            <Route path="/login" component={Login} />
        </Switch>
    )
}

export default SwitchRouter
function NavLinkRouter() {

    const history = useHistory()


    const handleLogin = () => {
        history.push('/Login')
        if(user.isLogin) {
            setUser({...user, isLogin: false})
            history.push('/')
        }
    }

    const { user, setUser } = useContext(LoginUserContext)

    console.log('nav link', user)                         //working fine

    return (
        <div className="navBar">
            <ul>
                <li><NavLink className="navlink" activeStyle={{ color: 'rgb(52,48,76)' }} strict to="/" exact>Home Page</NavLink></li>
                <li><NavLink className="navlink" activeStyle={{ color: 'rgb(52,48,76)' }} strict to="/contacts" >User Contacts</NavLink></li>
                <li><NavLink className="navlink" activeStyle={{ color: 'rgb(52,48,76)' }} strict to="/posts" >Posts</NavLink></li>
                <li><NavLink className="navlink" activeStyle={{ color: 'rgb(52,48,76)' }} strict to="/aboutme" >About Me</NavLink></li>
            </ul>
            <button className="btnLogin" onClick={handleLogin}>{user.isLogin ? 'Logout' : 'Login'}</button>
        </div>
    )
}

export default NavLinkRouter

为什么仅在 SwitchRouter.tsx 中不显示任何内容?以及如何获得用户的价值以将其用于条件渲染?

这是片段 在此处输入图像描述

4

0 回答 0