【问题标题】:Problems with looping when using redirect in route of React在 React 的路由中使用重定向时出现循环问题
【发布时间】:2020-07-10 23:44:21
【问题描述】:

有一个组件可以检测浏览器并返回有关不支持的浏览器的消息或返回重定向。该组件部分代码如下:

detectIE() {
    const ua = window.navigator.userAgent;
    const msie = ua.indexOf('MSIE ');
    console.log(msie);
    if (msie > 0) {
        return parseInt(ua.substring(msie + 5, ua.indexOf('.', msie)), 10);
    }
    return false;
}

render() {
    if (this.detectIE()) {
        return (
            <FullPageError
                title={''}
                image={<BntIconWrapper icon={<SvgPageErrorGeneric />} defaultColor={true} />}
                explanation={''}
                userOptions={''}
            ></FullPageError>
        );
    }
    return <Redirect to="/login" />;
}

该组件 (&lt;Route component={checkBrowser} /&gt;) 在根组件中呈现如下:

            <Switch>
                <Route component={checkBrowser} />
                <Route exact path="/login" component={checkLogin} />
                <Route exact path="/signin-oidc" component={checkSignInOidc} />
                <Route path="/error-page" component={ErrorPageContainer} />
                <Route path="/authorizeExternal" component={AuthorizeExternal} />
                <Route path="/" component={checkDarklyProjects} />
                <Route path="**" component={NotFound} />
            </Switch>

问题的核心是当detectIE()返回false,组件返回&lt;Redirect to="/login" /&gt;时发生循环。我认为循环发生是因为在&lt;Route component={checkBrowser} /&gt; 属性中path 不存在。但是这样做是为了让组件响应任何 URL。 检查浏览器后如何渲染其他控件?

【问题讨论】:

    标签: reactjs typescript routing react-component


    【解决方案1】:

    发生循环是因为当您重定向它时,基础组件(带有开关的组件)每次都会重新安装和重新渲染。 我的建议是不要将用户重定向到登录,因为您的组件 checkBrowser 仅检查浏览器(如果用户已登录,则不检查)以及将您的 checkBrowser 移动到交换机外部。

    我对您的代码的推荐

    render() {
        if (this.detectIE()) {
            return <Redirect to={"/error-page"} />;
        }
        // don't render anything to the DOM if its not an IE browser
        return null;
    }
    
    <checkBrowser/>
    <Switch>
       <Route exact path="/login" component={checkLogin} />
       <Route exact path="/signin-oidc" component={checkSignInOidc} />
       <Route path="/error-page" component={ErrorPageContainer} />
       <Route path="/authorizeExternal" component={AuthorizeExternal} />
       <Route path="/" component={checkDarklyProjects} />
       <Route path="**" component={NotFound} />
    </Switch>
    

    【讨论】:

      【解决方案2】:

      尝试将&lt;Route component={checkBrowser} /&gt;移到&lt;Switch&gt;&lt;/Switch&gt;之外

      【讨论】:

        猜你喜欢
        • 2021-11-10
        • 2019-08-23
        • 2020-12-31
        • 2021-08-30
        • 2020-11-11
        • 2019-10-29
        • 1970-01-01
        • 2019-07-16
        • 1970-01-01
        相关资源
        最近更新 更多