查看组件中先前的详细信息

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

我有一个组件,它调度一个操作,该操作调用一个 API,该 API 更新 redux 存储并通过选择器显示更新的存储

我遇到的麻烦是,当我离开组件并返回时,之前的信息会在 UI 中显示一秒钟,然后才会更新为新信息

"use client";
import React, { useState, useEffect, useCallback } from "react";

import { useAppDispatch, useAppSelector } from "@/lib/hooks/store.hooks";

import styles from "@/styles/components/_detail.module.scss";
import {
  getAlbum,
  selectAlbumDetail,
} from "@/lib/features/music/musicSlice";

import { AlbumDetail } from "@/shared/interfaces/music";

const initialAlbumDetail: AlbumDetail = {
  artists: [],
  image: "",
  name: "",
  release_date: "",
  spotify_link: "",
  tracks: [""],
  category: "",
};

const AlbumDetails = ({ params: { id } }: { params: { id: string } }) => {

const dispatch = useAppDispatch();
const [albumDetails, setAlbumDetails] =
    useState<AlbumDetail>(initialAlbumDetail);

const album: AlbumDetail = useAppSelector(selectAlbumDetail);

const [isFetching, setIsFetching] = useState(true);

const fetchAlbumDetails = useCallback(() => {
    setIsFetching(true);
    dispatch(getAlbum(id));
  }, [dispatch, id]);

  useEffect(() => {
    setAlbumDetails(initialAlbumDetail);
    fetchAlbumDetails();
  }, [fetchAlbumDetails]);

  useEffect(() => {
    if (album) {
      setAlbumDetails(album);
      setIsFetching(false);
    }
  }, [album]);

  if (isFetching) return <div>Loading...</div>;

  return (
    <>
      <div>{albumDetails.name}</div>
    </>
  );
};

export default AlbumDetails;
reactjs redux
1个回答
0
投票

我发现解决这个问题的最好方法是创建一个 redux 操作/减速器来清除细节

clearAlbumDetails: create.reducer((state) => {
      state.selectedAlbum = {} as AlbumDetail;
 }),

然后在我离开此页面时导航到的页面上分派操作。

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