无法访问this.setState

问题描述 投票:-1回答:1

我刚刚在订阅中实现了一个有效的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个回答
1
投票

componentDidMount之前:

const that = this;

然后再打电话:

that.setState();

在一个开明的周末阅读JavaScript“ this”。 “您还不知道JavaScript”是一本好书。

也请阅读反应钩子。

© www.soinside.com 2019 - 2024. All rights reserved.