【问题标题】:Can't access this.setState无法访问 this.setState
【发布时间】:2020-09-18 02:01:06
【问题描述】:

我刚刚在订阅上实现了一个有效的 Apollo 客户端监听器。订阅后,下面的代码可以获取并记录它。

但是,this.setState 似乎由于某种原因不起作用。当获取订阅时,应用程序会抛出 TypeError: this.setState is not a function

谁能解释一下原因?

    componentDidMount() {
        const SUBSCRIBE_POST = gql`
        subscription{
        postAdded{
            id
            message
            type
            created
            customers_ID
            customer{id,firstName}
        }
        }
        `;
        let response = null
        const {client} = this.props
        client.subscribe({query: SUBSCRIBE_POST})
            .subscribe({
                next(data) {
                    response = data.data.postAdded
                    console.log(response)
                    this.setState({list: response})
                },
                error(err) {console.error('err', err);},
            })
    }

【问题讨论】:

    标签: javascript react-native react-apollo apollo-client apollo-server


    【解决方案1】:

    在componentDidMount之前:

    const that = this;

    稍后再调用:

    that.setState();

    阅读 JavaScript “this”,度过一个开明的周末。 “You don't know JavaScript yet”是一本很好的读物。

    还阅读了 react hooks。

    【讨论】:

    • 吃奶大师!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-12-24
    • 1970-01-01
    • 2020-02-28
    • 1970-01-01
    • 2014-01-29
    • 2019-03-21
    • 1970-01-01
    相关资源
    最近更新 更多