createEntityAdapter

image.png

https://juejin.cn/post/6847902220415926279#heading-2

  1. const booksAdapter = createEntityAdapter<Book>({
  2. // Assume IDs are stored in a field other than `book.id`
  3. selectId: book => book.bookId,
  4. // Keep the "all IDs" array sorted based on book titles
  5. sortComparer: (a, b) => a.title.localeCompare(b.title)
  6. })

CRUD Functions

  • addMany
  • addOne
  • getInitialState
  • getSelectors
  • removeAll
  • removeMany
  • removeOne
  • setAll
  • setMany
  • setOne
  • selectId
  • sortComparer
  • updateMany
  • updateOne
  • upsertMany
  • upsertOne 插入

  • addOne 添加一个enity
  • addMany 添加多个enity,传递一个数组,数组中的元素要符合enity的对象结构
  • setAll 传递一个enity数组,数组中的元素要符合enity的对象结构,将当前已经存在的enity内的所有数据替换成传递的
  • removeOne 删除一个
  • removeMany 删除多个
  • removeAll 删除所有
  • updateOne 更新一个
  • updateMany 更新多个
  • upsertOne 接受一个entity 如果存在则更新 不存在则添加
  • upsertMany 接受多个entity 如果存在则更新 不存在则添加

    Selector Functions

    getSelectors()

  • selectIds 获取ID数组

  • selectEntities 获取实例对象,类似表
  • selectAll 返回一个所有实例对象的数组 但是属性都是用id展示
  • selectTotal 返回实例总数
  • selectById 通过id查询实例
  1. // 两种使用方式 其实就是指定了不同的作用域 一个是全局这种类型对象的一个是某一具体对象
  2. const store = configureStore({
  3. reducer: {
  4. books: booksReducer
  5. }
  6. })
  7. const simpleSelectors = booksAdapter.getSelectors()
  8. const globalizedSelectors = booksAdapter.getSelectors(state => state.books)
  9. // Need to manually pass the correct entity state object in to this selector
  10. const bookIds = simpleSelectors.selectIds(store.getState().books)
  11. // This selector already knows how to find the books entity state
  12. const allBooks = globalizedSelectors.selectAll(store.getState())

createAsyncThunk

https://redux-toolkit.js.org/api/createAsyncThunk

  1. export const fetchProducts = createAsyncThunk(
  2. "products/fetchProducts", async (_, thunkAPI) => {
  3. try {
  4. //const response = await fetch(`url`); //where you want to fetch data
  5. //Your Axios code part.
  6. const response = await axios.get(`url`);//where you want to fetch data
  7. return await response.json();
  8. } catch (error) {
  9. return thunkAPI.rejectWithValue({ error: error.message });
  10. }
  11. });
  12. const productsSlice = createSlice({
  13. name: "products",
  14. initialState: {
  15. products: [],
  16. loading: "idle",
  17. error: "",
  18. },
  19. reducers: {},
  20. extraReducers: (builder) => {
  21. builder.addCase(fetchProducts.pending, (state) => {
  22. state. products = [];
  23. state.loading = "loading";
  24. });
  25. builder.addCase(
  26. fetchProducts.fulfilled, (state, { payload }) => {
  27. state. products = payload;
  28. state.loading = "loaded";
  29. });
  30. builder.addCase(
  31. fetchProducts.rejected,(state, action) => {
  32. state.loading = "error";
  33. state.error = action.error.message;
  34. });
  35. }
  36. });
  37. export const selectProducts = createSelector(
  38. (state) => ({
  39. products: state.products,
  40. loading: state.products.loading,
  41. }), (state) => state
  42. );
  43. export default productsSlice;
  44. // 22323
  45. import { useSelector, useDispatch } from "react-redux";
  46. import {
  47. fetchProducts,
  48. selectProducts,
  49. } from "path/productSlice.js";
  50. Then Last part calling those method inside your competent like this
  51. const dispatch = useDispatch();
  52. const { products } = useSelector(selectProducts);
  53. React.useEffect(() => {
  54. dispatch(fetchProducts());
  55. }, [dispatch]);