React Router和useContext无法一起使用

时间:2020-04-13 13:43:09

标签: reactjs router use-context

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

NavigationBar.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中什么都不显示?以及如何获得用户的价值以将其用于条件渲染?

这是摘要 enter image description here

0 个答案:

没有答案