在useEffect中使用reducer状态

问题描述 投票:2回答:1

大家好👋🏻我有一个关于我们最喜欢的Hooks API的问题!

我想做什么?

我正在尝试从某个远程系统中获取照片。我将这些照片的Blob网址存储在我的由ID键入的减速器状态下。

我有一个辅助函数,该函数包装在useCallback挂钩返回的备注版本中。在我定义的useEffect中调用此函数。

问题⚠️

我的回调方法也就是helper函数,取决于部分reducer状态。每次获取照片时都会更新。这将导致组件再次在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;
  }
}
javascript reactjs redux react-redux
1个回答
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功能如何改变状态,因此可能需要进行一些微调。这个想法是:仅从您所依赖的商店中选择状态,这样商店的其他部分就不会引起重新渲染。

© www.soinside.com 2019 - 2024. All rights reserved.