我发现了许多类似的问题,但大多数解决方案都没有 redux 解决方案。我想在从 redux 商店删除项目后调用订阅。
以下是我取消所有订阅的代码,但我不确定我的做法是否正确!
const useFetchProperty = (propertyId, refresh = false) => {
const dispatch = useDispatch();
const property = useSelector(state => selectPropertyById(state, propertyId));
const isConnected = useIsConnected();
useEffect(() => {
let isSubscribed = true;
if (
isSubscribed &&
isConnected &&
(property === undefined || refresh === true)
) {
dispatch(fetchProperty({propertyId: propertyId}));
}
return () => (isSubscribed = false);
}, [dispatch, refresh, isConnected, property, propertyId]);
return property;
};
export default useFetchProperty;
CarDesign.js
const CardDesign = ({postId}) => {
const {t} = useContext(LocalizationContext);
const post = useFetchProperty(postId);
const currentLanguage = useSelector(currentAppLanguage);
const navigation = useNavigation();
//the rest show data would be here
}
你会看到我正在使用这两个
let isSubscribed = true;
和 return () => (isSubscribed = false);
。使用 dispatch 取消所有订阅和异步任务是否正确?
答案 0 :(得分:0)
您的 /drive1/MyDrive/ Foo.pdf
变量范围在 isSubscribe
内,因此无需执行以下操作
useEffect
原因是 - 当您的 useEffect 将采用新效果时,由于变量声明,isSubscribe 将始终具有 return () => (isSubscribed = false);
。由于范围在 true
内,因此删除返回将解决该问题
但如果你真的需要使用它,那么全局声明 useEffect
变量