【问题标题】:How do I call a function whenever my Apollo subscription gets triggered in React?每当我的 Apollo 订阅在 React 中被触发时,我如何调用函数?
【发布时间】:2018-06-05 16:12:10
【问题描述】:

我有一个反应组件,它在 apollo graphql 查询上使用 subscribeToMore 方法来更新自身的变化。这样做很好,但是我想在订阅进行更改时调用一些外部函数。我想在 UI 中显示一些事情已经改变的提示,让我们调用我们的函数“onUpdate”,我在哪里调用这个 onUpdate 函数?

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

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】:

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

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

    【讨论】:

    • 我想你可能误解了我的问题。我在问如何在我的数据更新时调用函数,而不是在我的组件更新时调用函数。在我的应用程序中使用这样的 ComponentDidUpdate() 函数会在数据发生任何更新之前触发。
    猜你喜欢
    • 2020-03-21
    • 2020-01-05
    • 2019-05-27
    • 2019-10-17
    • 2018-06-09
    • 2021-02-27
    • 2021-07-23
    • 2017-03-30
    • 1970-01-01
    相关资源
    最近更新 更多