未捕获的不变违规:超出最大更新深度

2023-12-30

当组件重复调用时可能会发生这种情况setState inside componentWillUpdate or componentDidUpdate。 React 限制嵌套更新的数量以防止无限循环。

我无法路由到authenticationRoute由于此错误而导致的目的地。

控制台输出:

index.js:1446 组件中出现上述错误:

in Redirect (at Auth.jsx:101)
in div (at Auth.jsx:116)
in Auth (created by Context.Consumer)
in Connect(Auth) (created by Route)
in Route (at App.js:27)
in Switch (at App.js:26)
in div (at App.js:46)
in App (created by Context.Consumer)
in Connect(App) (created by Route)
in Route (created by withRouter(Connect(App)))
in withRouter(Connect(App)) (at src/index.js:28)
in Router (created by BrowserRouter)
in BrowserRouter (at src/index.js:27)
in Provider (at src/index.js:26)
import React, { Component } from 'react';
import Input from '../../components/Input/input';
import Button from '../../components/Button/button';
import { connect } from 'react-redux';
import { Redirect } from 'react-router-dom';
import * as service from '../../services/AuthService';

 class Auth extends Component {
     state = {
        controls: {
            username: {
               //..
            },
            password: {
               //..
                },
                valid: false,
                touched: false
            }
        }
    }

    componentDidMount () {
        if ( this.props.isAuthenticated && this.props.authRedirectPath !== '/' ) {
            this.props.onSetAuthRedirectPath('/home');
        }
    }


    handleSubmit=(event)=> {
        event.preventDefault();
        this.props.auth(this.state.controls.username.value,this.state.controls.password.value)
       
    }
    render() {

        let errorMessage = null;
        let button= button=<Button btnType="Success">Login</Button>
        let authRedirect = null;
        if (this.props.isAuthenticated) {
            **authRedirect = <Redirect to={this.props.authRedirectPath}/>** //line 101
        }
        return (
        <div>
            {authRedirect}
                        <form onSubmit={this.handleSubmit}>
                           {form}
                        {button}
                        </form>
              
            </div>
        )
    }
}

export default connect( mapStateToProps, mapDispatchToProps )( Auth );

您如何检查身份验证?

最好在 redux-store 中初始化 isAuthenticated,这样您就可以在渲染之前在组件中全局使用它

所以,而不是

if (this.state.isAuthenticated) {routes=<div>..</div>}

Try

if (this.props.isAuthenticated{routes=<div>..</div>}

实例属性

props

this.props 包含由调用者定义的 props 这个组件。有关 props 的介绍,请参阅组件和 Props。

state

this.state 包含特定于此组件的数据,这些数据可能 随着时间的推移而变化。状态是用户定义的,它应该是一个简单的 JavaScript 对象。

有关状态的更多信息,请参阅状态和生命周期。React.Component 生命周期 https://reactjs.org/docs/react-component.html#props

切勿直接改变 this.state,因为之后调用 setState() 可能会替换您所做的改变。将 this.state 视为不可变的。

另外,确保 mapStateToProps 指向您的减速器

return {isAuthenticated : state.{减速器}.isAuthenticated}

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

未捕获的不变违规:超出最大更新深度 的相关文章

随机推荐