This React component manages the data and then gives it as props to another child component, and Этот дочерний компонент отдает от реагирования базовый компонент.
Код: Выделить всё
import { useEffect, useState } from 'react';
import _ from 'lodash';
const useSyncedData = ({
source,
mapState = (data) => ({ ...data }),
listenTo = 'update refresh',
useDebounce = true,
onMount = () => {},
onUnmount = () => {},
onTrigger = () => {},
}) => {
const [localData, setLocalData] = useState(mapState(source));
let isListening = true;
let updateState = () => {
if (isListening) {
setLocalData(mapState(source));
onTrigger();
}
};
if (useDebounce) {
updateState = _.debounce(updateState);
}
useEffect(() => {
const eventList = Array.isArray(listenTo) ? listenTo.join(' ') : listenTo;
source.on(eventList, updateState);
onMount();
return () => {
isListening = false;
source.off(eventList, updateState);
onUnmount();
};
}, [source]);
return localData;
};
export default useSyncedData;
Подробнее здесь: https://stackoverflow.com/questions/796 ... and-models
Мобильная версия