大家好??我对我们最喜欢的Hooks API有疑问!
我正在尝试从某个远程系统中获取照片。我将这些照片的Blob网址存储在我的由ID键入的减速器状态下。
我有一个辅助函数,该函数包装在useCallback
挂钩返回的备注版本中。在我定义的useEffect
中调用了此函数。
我的回调也称为helper函数,它取决于化简器状态的一部分。每次获取照片时都会更新。这将导致组件再次在useEffect
中运行效果,从而导致无限循环。
component renders --> useEffect runs ---> `fetchPhotos` runs --> after 1st photo, reducer state is updated --> component updates because `useSelector`'s value changes ---> runs `fetchPhotos` again ---> infinite
const FormViewerContainer = (props) => {
const { completedForm, classes } = props;
const [error, setError] = useState(null);
const dispatch = useDispatch();
const photosState = useSelector(state => state.root.photos);
// helper function which fetches photos and updates the reducer state by dispatching actions
const fetchFormPhotos = React.useCallback(async () => {
try {
if (!completedForm) return;
const { photos: reducerPhotos, loadingPhotoIds } = photosState;
const { photos: completedFormPhotos } = completedForm;
const photoIds = Object.keys(completedFormPhotos || {});
// only fetch photos which aren't in reducer state yet
const photoIdsToFetch = photoIds.filter((pId) => {
const photo = reducerPhotos[pId] || {};
return !loadingPhotoIds.includes(pId) && !photo.blobUrl;
});
dispatch({
type: SET_LOADING_PHOTO_IDS,
payload: { photoIds: photoIdsToFetch } });
if (photoIdsToFetch.length <= 0) {
return;
}
photoIdsToFetch.forEach(async (photoId) => {
if (loadingPhotoIds.includes(photoIds)) return;
dispatch(fetchCompletedFormPhoto({ photoId }));
const thumbnailSize = {
width: 300,
height: 300,
};
const response = await fetchCompletedFormImages(
cformid,
fileId,
thumbnailSize,
)
if (response.status !== 200) {
dispatch(fetchCompletedFormPhotoRollback({ photoId }));
return;
}
const blob = await response.blob();
const blobUrl = URL.createObjectURL(blob);
dispatch(fetchCompletedFormPhotoSuccess({
photoId,
blobUrl,
}));
});
} catch (err) {
setError('Error fetching photos. Please try again.');
}
}, [completedForm, dispatch, photosState]);
// call the fetch form photos function
useEffect(() => {
fetchFormPhotos();
}, [fetchFormPhotos]);
...
...
}
我找到了另一种方法来提取照片,也就是通过调度动作并使用工作人员传奇来完成所有提取操作。这消除了组件中对帮助者的所有需要,因此不需要useCallback
,因此无需重新渲染。然后,useEffect仅取决于dispatch
。
我在使用hooks API的思维模式上苦苦挣扎。我看到了明显的问题,但是我不确定如果不使用thunk和sagas之类的redux中间件,怎么办?
减速器功能
export const initialState = {
photos: {},
loadingPhotoIds: [],
};
export default function photosReducer(state = initialState, action) {
const { type, payload } = action;
switch (type) {
case FETCH_COMPLETED_FORM_PHOTO: {
return {
...state,
photos: {
...state.photos,
[payload.photoId]: {
blobUrl: null,
error: false,
},
},
};
}
case FETCH_COMPLETED_FORM_PHOTO_SUCCESS: {
return {
...state,
photos: {
...state.photos,
[payload.photoId]: {
blobUrl: payload.blobUrl,
error: false,
},
},
loadingPhotoIds: state.loadingPhotoIds.filter(
photoId => photoId !== payload.photoId,
),
};
}
case FETCH_COMPLETED_FORM_PHOTO_ROLLBACK: {
return {
...state,
photos: {
...state.photos,
[payload.photoId]: {
blobUrl: null,
error: true,
},
},
loadingPhotoIds: state.loadingPhotoIds.filter(
photoId => photoId !== payload.photoId,
),
};
}
case SET_LOADING_PHOTO_IDS: {
return {
...state,
loadingPhotoIds: payload.photoIds || [],
};
}
default:
return state;
}
}
答案 0 :(得分:1)
您可以将photoIdsToFetch
计算逻辑包含在选择器函数中,以减少由于状态更改而导致的渲染次数。
const photoIdsToFetch = useSelector(state => {
const { photos: reducerPhotos, loadingPhotoIds } = state.root.photos;
const { photos: completedFormPhotos } = completedForm;
const photoIds = Object.keys(completedFormPhotos || {});
const photoIdsToFetch = photoIds.filter(pId => {
const photo = reducerPhotos[pId] || {};
return !loadingPhotoIds.includes(pId) && !photo.blobUrl;
});
return photoIdsToFetch;
},
equals
);
但是选择器函数没有被记忆,它每次都会返回一个新的数组对象,因此对象相等性在这里不起作用。您将需要提供一个isEqual方法作为第二个参数(它将比较两个数组以实现值相等),以便选择器将在ID相同时返回相同的对象。您可以编写自己的图书馆或deep-equals
库,例如:
import equal from 'deep-equal';
fetchFormPhotos
将仅依赖于[photoIdsToFetch, dispatch]
。
我不确定您的reducer功能如何改变状态,因此这可能需要一些微调。这个想法是:只从您所依赖的商店中选择状态,这样商店的其他部分就不会引起重新渲染。