使用API响应说明Redux工具包中的项目批次

l0oc07j2  于 2022-11-12  发布在  其他
关注(0)|答案(1)|浏览(120)

我正在为用户编写一个书签列表。我想在一个数组中存储API响应。我正在使用Google Book API。我正在使用Redux Toolkit。
用户可以在他的个人愿望列表中添加书籍,并显示和做了一些操作,我需要在国家股票书籍信息添加。
目前我只有1本书的库存原因,如果我试图添加另一个在国家,这一个变化与新的一个只有。我需要股票所有的书籍添加。
有什么想法吗?
bookSlice.js

import { createSlice, createAsyncThunk } from "@reduxjs/toolkit";
import { BOOKS_BY_ID } from "../../services/api/googleBooks";

export const getBook = createAsyncThunk(
    "book/getBook",
    async ({ bookid }) => {
        const response = await fetch(`${BOOKS_BY_ID}${bookid}`);
        const data = await response.json();
        return data;
    }
);

const bookSlice = createSlice({
    name: "book",
    initialState: {
        list: [],
        status: null,
    },
    reducers: {},
    extraReducers: {
        [getBook.pending]: (state, action) => {
            state.status = "loading";
        },
        [getBook.fulfilled]: (state, action) => {
            state.status = "success";
            state.list = action.payload;
        },
        [getBook.rejected]: (state, action) => {
            state.status = "failed";
        },
    },
});

export default bookSlice.reducer;

FetchBookBookmarked.js

useEffect(() => {
    // let allBook = [];
    let ignore = false;
    bookInfos?.map(async (book) => {
      dispatch(getBook({ bookid: book }));

      await axios.get(`${BOOKS_BY_ID}${book}`).then((res) => {
        // allBook.push(res.data);
        if (!ignore) {
          setBookDetail((oldValues) => [...oldValues, res.data]);
        }
      });
    });
    return () => {
      ignore = true;
    };
  }, [bookInfos, dispatch]);
6ie5vjzr

6ie5vjzr1#

将图书数据推送到列表中。
替换以下行:

state.list = action.payload;

收件人:

state.list.push(action.payload)

为避免重复,您可以在添加ID之前检查它:

const bookAlreadyExists = state.list.some(book => book.id === action.payload.id)
if (!bookAlreadyExists) {
  state.list.push(action.payload)
}

相关问题