1 回答

TA貢獻1936條經(jīng)驗 獲得超7個贊
保持useObservable鉤子隔離,并創(chuàng)建一個可觀察值(記憶到位置 id)以傳遞給它:
const useObservable = (observable, setter) => {
useEffect(() => {
let subscription = observable.subscribe(result => {
setter(result);
});
return () => subscription.unsubscribe()
},
[observable, setter]
);
};
const LocationItem = ({ location }) => {
const [readings, setReadings] = useState([]);
const dataObservable = useMemo(() => {
return collectionData(
db
.collection('mimirReading')
.where('locationId', '==', location.id)
.orderBy('timestamp', 'desc')
.limit(48)
);
}, [location.id]);
useObservable(dataObservable, setReadings);
return (
<ol>
{readings.map((r) => (
<li>{r.timestamp}</li>
))}
</ol>
);
};
或者,我進一步建議將狀態(tài)的所有權(quán)更改為useObservable:
const useObservable = (observable) => {
const [value, setValue] = useState();
useEffect(() => {
let subscription = observable.subscribe((result) => {
setValue(result);
});
return () => subscription.unsubscribe();
}, [observable]);
return value;
};
這樣你就不需要外部狀態(tài)設置器,它總是在鉤子內(nèi)處理。您還可以使用setStatewithinuseObservable來捕獲可觀察對象的錯誤和完成事件。
添加回答
舉報