如何在 React reduxjs/toolkit 中删除项目后刷新页面?

How to refresh page after deleting item in React reduxjs/toolkit?

我正在使用:

删除项目(对我来说是 wordSet)后,我需要更新我的 UI。现在,项目仅从数据库中删除并更新 UI 我必须刷新页面。

你能告诉我如何从 UI 中删除项目吗? 我可以使用 wordSets.filter 到 return 新数组,但这是个好方法吗?

我的代码:

export const deleteWordSet = createAsyncThunk<void, string>(
  'wordSet/deleteWordSet',
  async (id: string, thunkAPI) => {
    try {
      const accessToken = getToken();
      if (!accessToken) thunkAPI.rejectWithValue('Invalid token');
      const config = {
        headers: { Authorization: `Bearer ${accessToken}` },
      };
      await api.delete(`/wordSet/${id}`, config);
    } catch (error) {
      thunkAPI.rejectWithValue(error);
    }
  }
);


export const fetchWordSets = createAsyncThunk<IWordSet[]>(
  'wordSet/fetchWordSets',
  async (_, thunkAPI) => {
    try {
      const accessToken = getToken();
      if (!accessToken) thunkAPI.rejectWithValue('Invalid token');
      const config = {
        headers: { Authorization: `Bearer ${accessToken}` },
      };
      const response: IApiResponse<IWordSet[]> = await api.get('/wordSet', config);
      const data = response.data.data;
      return data;
    } catch (error) {
      return thunkAPI.rejectWithValue(error);
    }
  }
);



const WordSetList = () => {
  const { wordSets } = useAppSelector(state => state.wordSet);
  const dispatch = useAppDispatch();
  useEffect(() => {
    dispatch(fetchWordSets()).unwrap();
  }, [dispatch]);
  return (
    <div className={styles.container}>
      {wordSets.map(wordSet => (
        <WordSetListItem key={wordSet._id} {...wordSet} />
      ))}
    </div>
  );
};

export default WordSetList;

根据 Jamal 的提示做了一些修改

现在在我的 asynthunk 上,我正在 return 删除单词的 ID,然后在完成删除工作集时过滤数据。

builder.addCase(deleteWordSet.fulfilled, (state, action) => {
  state.isFetching = false;
  state.wordSets = state.wordSets.filter(wordSet => wordSet._id !== action.payload);
});

您需要将更新的数据传递给您的减速器,这样 UI 将在不刷新的情况下得到更新。将更新后的数据作为有效载荷发送,并根据传递的有效载荷从那里更新减速器的状态。