ReactJS-PrivateRoute函数中的最大更新深度超出错误

我正在使用专用路由器的概念来保​​护我的应用程序,但是在未设置某些内容的情况下也会进行重定向。

我收到以下代码中的错误:Maximum update depth exceeded

function PrivateRoute ({component: Component,...rest }) {
    const stateFn = state => state.init;
    const init = useSelector(stateFn)

    const isInstalled = init.installationComplete;
    const isUserStored = localStorage.getItem('user');

    return (
        <Route
            render={props =>
                isUserStored && isInstalled ? (
                    <Component {...props} {...rest} />
                ) : !isInstalled  ? (
                    <Redirect
                        to={{
                            pathname: "/install",state: { from: props.location }
                        }}
                    />
                ) : (
                    <Redirect to={{ pathname: '/login',state: { from: props.location } }} />
                )
            }
        />
    );
}

我在做错什么导致了错误?为什么?

我在这里使用PrivateRoute:

class App extends React.Component<any,any> {
    constructor(props) {
        super(props);

        const { dispatch } = this.props;

        dispatch(initactions.loadInit());

        history.listen((location,action) => {
            // clear alert on location change
            dispatch(alertactions.clear());
        });
    }

    render() {
        const { alert } = this.props;
        return (
            <React.Fragment>
                <Helmet titleTemplate="%s | conductor" defaultTitle="conductor"/>
                <StylesProvider injectFirst>
                    <MuiThemeProvider theme={theme[0]}>
                        <ThemeProvider theme={theme[0]}>
                            {alert.message &&
                                <Alert mb={4} severity={alert.type}>{alert.message}</Alert>
                            }
                            <Router history={history}>
                                <div>
                                    <PrivateRoute component={HomePage} />
                                    <Route path="/login" component={LoginPage} />
                                    <Route path="/install" component={InstallationPage} />
                                </div>
                            </Router>
                        </ThemeProvider>
                    </MuiThemeProvider>
                </StylesProvider>
            </React.Fragment>
        );
    }
}

lvyinkiller 回答:ReactJS-PrivateRoute函数中的最大更新深度超出错误

您的PrivateRoute将在未定义路径的情况下渲染Route,这意味着它将对'/'路径作出反应。并且您将PrivateRoute用作路由的第一个组件,因此它将实际处理所有内容(因为所有内容均以“ /”开头,因此“ / login”将由您的“ /”路由处理),因此您应该<Route path='/' exact .../> exact 属性将使此路由仅在url为'/'时才有效。另一种选择是将PrivateRoute作为“路由表”(放置<Route>元素的位置)中的最后一个组件

本文链接:https://www.f2er.com/1266162.html

大家都在问