【问题标题】:Does useSelector automatically unsubscribe the component from store updates when it is unmounted?卸载时,useSelector 是否会自动从商店更新中取消订阅组件?
【发布时间】:2021-03-09 07:02:06
【问题描述】:

我正在查看作为 react-redux 库一部分的 useSelector 的源代码。

我想知道useSelector 是否会在组件卸载时自动从 redux 存储更新中取消订阅组件,类似于在 Redux 中使用通过调用 store.subscribe 返回的 unsubscribe 函数?或者,如果另一个组件更改了该状态,它是否仍会订阅此类更改?

【问题讨论】:

  • 是的,在创建新状态时将不再调用传递给 useSelector 的回调,并且当组件卸载时,react-redux 不会对组件进行更新。

标签: reactjs redux react-redux


【解决方案1】:

是的,useSelector 在组件卸载时显式取消订阅存储。每https://github.com/reduxjs/react-redux/blob/v7.2.2/src/hooks/useSelector.js#L81

  useIsomorphicLayoutEffect(() => {
    function checkForUpdates() {
      try {
        const newSelectedState = latestSelector.current(store.getState())

        if (equalityFn(newSelectedState, latestSelectedState.current)) {
          return
        }

        latestSelectedState.current = newSelectedState
      } catch (err) {
        // we ignore all errors here, since when the component
        // is re-rendered, the selectors are called again, and
        // will throw again, if neither props nor store state
        // changed
        latestSubscriptionCallbackError.current = err
      }

      forceRender()
    }

    subscription.onStateChange = checkForUpdates
    subscription.trySubscribe()

    checkForUpdates()

    return () => subscription.tryUnsubscribe() // unsubscribes here
  }, [store, subscription])

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-08-09
    • 2014-11-16
    • 2020-07-29
    • 1970-01-01
    • 2021-12-23
    • 2017-04-06
    • 2021-02-25
    • 2019-06-12
    相关资源
    最近更新 更多