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

时间:2019-02-20 16:13:34

标签: javascript reactjs

当组件在setStatecomponentWillUpdate内重复调用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 );

1 个答案:

答案 0 :(得分:2)

您如何检查身份验证?

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

所以,而不是

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

尝试

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

实例属性

道具

  

this.props包含由调用者定义的道具   此组件。有关道具的介绍,请参见组件和道具。

状态

  

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

有关状态的更多信息,请参见状态和生命周期。 React.Component Lifecycle

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

还请确保mapStateToProps指向减速器

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