首页 > 解决方案 > React.Js 上下文和最大深度超出

问题描述

我收到以下错误: Unhandled Rejection (Invariant Violation): Maximum update depth exceeded. This can happen when a component repeatedly calls setState inside componentWillUpdate or componentDidUpdate. React limits the number of nested updates to prevent infinite loops.

当我尝试运行给定的突变时出现此错误,突变是

<Mutation mutation={LOGIN}>
    { (login, {data,loading,error}) => {
        if(loading)  return(<h1> Loading... </h1>);
        if(data) this.context.login(
            data.login.token, 
            data.login.userId, 
            data.login.tokenExpiration);
        return(
            <button onClick={
                e => {
                e.preventDefault();
                    login({
                        variables: {
                            email: this.state.email,
                            password: this.state.password
                        }
                    })
                }}>
                Login
            </button>
        );
    }}
</Mutation>

如果我删除if(data) login(...)返回上方的块,它将正常工作。

这是我使用 import React from 'react' 的上下文;

export default React.createContext({
    token: null,
    userId: null,
    login: (token,userId,tokenExpiration) => {},
    logout: () => {},
});

它将 soem JSX 包装在我的主页中,例如

<AuthContext.Provider value={
    {
        token: this.state.token, 
        userId: this.state.userId, 
        login: this.login, 
        logout:this.logout
    }
}>

登录和注销方法是

login = (token,userId,tokenExpiration) => {
        this.setState({ token:token, userId: userId });
    }

    logout = () => {
        this.setState({token:null, userId: null});
    }

我 100% 正确导入了所有内容,graphQL 突变也返回了我们想要的数据。React 告诉我错误在我的登录方法中,但我看不出有任何问题。有什么想法吗?我对上下文 api 不是很有经验。

标签: javascriptreactjsgraphqlreact-apollo

解决方案


推荐阅读