【问题标题】:url redirected successfully, but component is not called when using redirect on react js typescripturl重定向成功,但在react js typescript上使用重定向时未调用组件
【发布时间】:2021-06-22 04:22:07
【问题描述】:

我正在使用 react js 打字稿创建身份验证。当登录不成功或 isLogin = false 时,我想将 URL 重定向到路径 "/" ,该路径具有 Login 组件。当登录成功或isLogin = true 时,我想将 URL 重定向到具有仪表板组件的仪表板路径。到这里URL已经成功重定向,但是组件没有被调用。

function App() {
    const { state } = useContext(AuthContext)
    
    return (
        <BrowserContext>
            <Switch>
                {!state.isLogin
                    ? <Redirect to="/" />
                    : <Redirect to="/dashboard" />
                }
                <Route exact path="/" component={Login} />
                <Route path="/dashboard" component={Dashboard} />
                <Route path="/register" component={Register} />
            </Switch>
        </BrowserContext>
    )
}

【问题讨论】:

    标签: reactjs react-router react-router-dom


    【解决方案1】:

    问题是您编写的重定向逻辑仅在 App 组件初始化时运行一次。因此,对state.isLogin 的任何后续更改都不会触发重新渲染。

    这里需要使用useEffect钩子。

    您可以在钩子中编写重定向逻辑并添加 state.isLogin 作为依赖项,更新后将触发重新呈现您的重定向逻辑。

    【讨论】:

    • 每次上下文的值发生变化,所有组件的消费者都会重新渲染。
    • 我已经尝试过您的建议,但它使重定向不起作用。还有其他解决方案吗?感谢您花时间回答
    • @Isaac 在这种情况下我们不需要使用效果?
    • 是的,你可以试试其他答案,但useEffect肯定帮不了你
    【解决方案2】:

    问题是Switch 组件渲染首先 适合RouteRedirect 组件。所以正如执行到达:

    {!state.isLogin
        ? <Redirect to="/" />
        : <Redirect to="/dashboard />
    }
    

    它根据标志呈现第一个重定向组件或第二个重定向组件,并且永远不会进一步到达 Route 块。

    您有几个选项可以让它发挥作用。

    • 声明性:
    function App() {
        const { state } = useContext(AuthContext)
        
        return (
            <BrowserContext>
                <Switch>
                    <Route exact path="/" render={() => {
                        if (state.isLogin) return <Redirect to="/dashboard" />
              
                        return <Login />
                    }} />
                    {!state.isLogin ? <Redirect to="/" /> : null}
                    <Route path="/dashboard" component={Dashboard} />
                    <Route path="/register" component={Register} />
                </Switch>
            </BrowserContext>
        )
    }
    

    如果路径是/,那么它将检查isLogin 标志并重定向到/dashboard,如果它设置并呈现Login,如果不是。 如果路径不是/ 并且没有设置isLogin 标志,它将重定向到/。如果设置了isLogin,它将落入下一个Route 组件。

    • 势在必行 显示完整代码的时间很长。这将需要大量的重构。您必须将BrowserRouter 移动到App 的父组件。使App 可以访问来自withRouter hoc 的history 属性。然后在isLogin发生变化时使用React.useEffect执行重定向:
    const { history } = props
    ...
    React.useEffect(() => {
        history.push(state.isLogin ? "/dashboard" : "/")
    }, [state.isLogin, history])
    

    【讨论】:

      猜你喜欢
      • 2020-03-25
      • 1970-01-01
      • 2018-05-20
      • 1970-01-01
      • 2019-10-13
      • 2020-08-28
      • 1970-01-01
      • 2018-05-28
      • 1970-01-01
      相关资源
      最近更新 更多