在redux工具包中从一个切片到另一个切片访问存储数据,以在API中传递自定义参数

omjgkv6w  于 2023-02-04  发布在  其他
关注(0)|答案(1)|浏览(161)

剖面切片:

import { createSlice, createAsyncThunk } from '@reduxjs/toolkit'
import { IMAGE_API, ACCESS_KEY } from "../../app/utils/constant";

export const getImages = createAsyncThunk('images', async () => {
  return fetch(`${IMAGE_API + ACCESS_KEY}`).then((res) =>
    res.json()
  )
})
console.log(IMAGE_API + ACCESS_KEY);

const ProfilePicSlice = createSlice({
  name: 'imageList',
  initialState: {
    images: [],
    loading: false,
  },
  extraReducers:  (builder) => {
    builder.addCase(getImages.pending, (state) => {
      state.loading = true;
    })
    builder.addCase(getImages.fulfilled, (state, action) => {
      state.loading = false;
      state.images.push(action.payload);
      console.log(action.payload)
    })
    builder.addCase(getImages.rejected, (state) => {
      state.loading = true;
    })
  }
});

export default ProfilePicSlice.reducer

表格切片:

import { createSlice } from "@reduxjs/toolkit";

const initialState = []

const UserSlice = createSlice({
  name: 'users',
  initialState,
  reducers: {
    addUser: (state, action) => {
      state.push(action.payload);
    }
  }
});

export const {addUser} = UserSlice.actions;
export default UserSlice.reducer;

我想在asyncThunk“${IMAGE_API +”自定义参数“+ ACCESS_KEY}中的API URL中添加自定义参数
自定义参数应该来自表单切片数据。

bq9c1y66

bq9c1y661#

redux-toolkit异步thunk可以访问ThunkAPI,其中包含一个函数来获取当前redux状态对象,它是传递给thunk回调函数的第二个参数。从这里你可以选择你需要的状态值。
请参阅有效负载创建器。
示例:

export const getImages = createAsyncThunk(
  'imageList /images',
  (_, { getState }) => {
    const store = getState();

    const param = state.users./* access into state to get property */;

    return fetch(`${IMAGE_API}${param}${ACCESS_KEY}`)
      .then((res) => res.json());
  }
);

相关问题