【问题标题】:What if an rxjs Observable Depends on React State?如果 rxjs Observable 依赖于 React 状态怎么办?
【发布时间】:2020-11-02 20:36:01
【问题描述】:

将反应状态订阅到rxjs Observable 很简单:

import React, { useState, useEffect } from 'react'
import * as r from 'rxjs'
import * as ro from 'rxjs/operators'

const obs$: r.Observable<number> = ...

const App = () => {
  const [count, setCount] = useState(0)
  useEffect(() => {
    const subscription = obs$.subscribe(setCount)
    return () => subscription.unsubscribe()
  }, [])
  return (...)
}

但是,如果我的Observable 依赖于某个反应状态并且我不想在每次更改时都重新订阅呢?

const App = () => {
  const [count, setCount] = useState(0)
  const [otherCount, setOtherCount] = useState(0)
  useEffect(() => {
    const subscription = obs$.pipe(
      ro.map(c => c + otherCount),
    ).subscribe(setCount)
    return () => subscription.unsubscribe()
  }, [otherCount]) // this will resubscribe every time `otherCount` changes
  return (...)
}

如果obs$ 每次启动都会做一些昂贵的事情怎么办?有没有一种安全的方法可以在每次otherCount 更改时无需重新订阅?

【问题讨论】:

  • 根据您希望它的工作方式,可以将状态更改设为可观察的,然后将其中两个与“zip”结合起来。

标签: reactjs rxjs react-hooks observable use-effect


【解决方案1】:

这里更深层次的问题是使用 react useEffect - SO post 进行事件处理

我最终选择了 this answer for that post 的这个选项

const App = () => {
  const [count, setCount] = useState(0)
  const [otherCount, setOtherCount] = useState(0)
  const otherCountRef = useRef(otherCount)
  useEffect(() => {
    otherCountRef.current = otherCount
  }, [otherCount])
  useEffect(() => {
    const subscription = obs$.pipe(
      ro.map(c => c + otherCountRef.current),
    ).subscribe(setCount)
    return () => subscription.unsubscribe()
  }, [])
  return (...)
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-08-04
    • 1970-01-01
    • 2011-06-30
    • 1970-01-01
    • 2019-06-14
    • 1970-01-01
    • 2021-05-01
    • 2015-08-30
    相关资源
    最近更新 更多