React路由中使用重定向时出现循环问题

问题描述 投票:0回答:2

[具有检测浏览器并返回有关不支持的浏览器或返回重定向消息的组件。该组件的代码部分在下面:

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" />;
}

此组件(<Route component={checkBrowser} />)在根组件中呈现为波纹管:

            <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且组件返回<Redirect to="/login" />时发生循环。我认为出现循环是因为<Route component={checkBrowser} />属性中path不存在。但这是为了使组件能够响应任何URL。检查浏览器后如何呈现其他控件?

reactjs typescript routing react-component
2个回答
0
投票

尝试将<Route component={checkBrowser} />移动到<Switch></Switch>之外


0
投票

之所以会发生循环,是因为在您重定向它时,每次都会重新安装并重新渲染基本组件(带有开关的组件)。我的建议是不要重定向用户以登录,因为您的组件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>
© www.soinside.com 2019 - 2024. All rights reserved.