Я хочу обновить состояние моего компонента внутри useEffect
, но сравнивать и обновлять состояние только в случае изменения объекта.
Как я могу это сделать?
Это мой текущий код:
const Features = ({ fetchProductFeature, productFeature }) => {
const [features, setFeatures] = useState([]);
const usePrevious = value => {
const ref = useRef();
useEffect(() => {
ref.current = value;
});
return ref.current;
};
const myPreviousState = usePrevious(productFeature);
useEffect(() => {
fetchProductFeature();
if (myPreviousState && !_.isEqual(myPreviousState, productFeature)) {
let features =
productFeature &&
fetchProductFeature.data &&
fetchProductFeature.data.map(feature => ({
label: feature,
value: false
}));
setFeatures(features);
}
}, [fetchProductFeature, productFeature, myPreviousState]);
console.log("productFeature", productFeature);
if (productFeature.loading) return "Loading...";
if (productFeature.error) return "Error";
if (productFeature.data) {
return (
<ErrorBoundary>
<Card>
{'UI CODE HERE'}
</Card>
</ErrorBoundary>
);
}
return null;
};
const mapStateToProps = ({ accountsReducer }) => ({
productFeature: accountsReducer.productFeature
});
const mapDispatchToProps = dispatch => ({
fetchProductFeature: () => dispatch(fetchProductFeature())
});
export default connect(mapStateToProps, mapDispatchToProps)(Features);