【发布时间】:2019-10-08 22:27:09
【问题描述】:
大家好??????我对我们最喜欢的 Hooks API 有疑问!
我想做什么?
我正在尝试从某个远程系统获取照片。我将这些照片的 blob url 存储在由 id 键入的 reducer 状态中。
我在 useCallback 钩子返回的记忆版本中包装了一个辅助函数。这个函数在我定义的useEffect中调用。
问题⚠️
我的回调又名辅助函数取决于减速器状态的一部分。每次获取照片时都会更新。这会导致组件再次在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 和 saga 等 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;
}
}
【问题讨论】:
-
不应该是:const { photos: reducerPhotos, loadingPhotoIds } = photosState; ?
-
应该是:const { photos: reducerPhotos**, loadingPhotoIds } = photosState;在“fetchFormPhotos”回调中。
标签: javascript reactjs redux react-redux