【发布时间】: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