每当我的Apollo订阅在React中被触发时,如何调用函数?

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

我有一个react组件,它在apollo graphql查询上使用subscribeToMore方法来更新自己。它做得很好,但我想在订阅获得更改时调用一些外部函数。我想在UI中显示一些事情已经改变的提示,让我们调用我们的函数'onUpdate',我在哪里调用这个onUpdate函数?

我的组件在render函数之前有一些看起来像这样的代码:

subscribeToNewPoints = () => {
  this.props.studentSessionPointsQuery.subscribeToMore({
    document: NEW_POINT_STUDENT_SESSION_SUBSCRIPTION,
    variables,
    updateQuery: (previous, { subscriptionData }) => {
      const newAllPoints = [
        subscriptionData.data.Point.node,
        ...previous.allPoints
      ]
      const result = {
        ...previous,
        allPoints: newAllPoints
      }
      return result
    }
  })
}

componentDidMount() {
    this.subscribeToNewPoints()
}

我应该把我的onUpdate函数放在这里,还是其他地方?

请原谅我,如果在另一个问题中回答这个问题,但我能找到的所有其他人似乎都在询问如何更新查询的缓存或如何让订阅首先工作。

reactjs react-apollo graphql-subscriptions
1个回答
0
投票

React有它的生命周期事件ComponentWillUpdate,它在组件获得更新之前调用。或者您可以使用在组件获得更新后调用的ComponentDidUpdate

ComponentWillUpdate() {
 /*called just before an update */
 onUpdateFunc()
}

ComponentDidUpdate() {
 /*called just after an update */
 onUpdateFunc()
}
© www.soinside.com 2019 - 2024. All rights reserved.