如何在Redux Toolkit中使用头文件创建POST API请求

rsl1atfo  于 2023-10-19  发布在  其他
关注(0)|答案(2)|浏览(126)

这是我的数据

var data = JSON.stringify({
  "RegisterOnlyNewLead": true,
  "LeadFields": [
    {
      "Attribute": "mx_Portal_Confirm_Password",
      "Value": "Samplepassword12345"
    },
    {
      "Attribute": "mx_Portal_Password",
      "Value": "Samplepassword12345"
    },
    {
      "Attribute": "EmailAddress",
      "Value": "[email protected]"
    }
  ]

Axios配置文件

var config = {
  method: 'post',
  url: 'https://portalapi.leadsquared.com/api/Authentication/Register?accessKey=u$rab680a72fbd14b1b1cb91a7a91b2c330&secretKey=d39dc85211959db0115594530c07a8268243f937',
  headers: {
    'Authorization': 'eUxOeEVXLytCSFh4RHVrNk4ySDhsS3U1TVVOMG44a0dIdGJwQ0c3T1NRbHlvNmczM0tLV0VYK3NrNEJ1Yi9adGo0TWdPK1hRWEJnMU5GRE9rbnIvbGxiNGJ4aUlwdzByMWU3VHB6enF5bUlmc2UxTUJpRUVUdUxNV083VFpMTXptUVVkNXpZMXIzbEt1U2tBODdwVm9BRUY0NmpyeDVWYkxGTzhXOUtHaXpnN0l5em5WNTc5eXZBRVFZajYvRmhrSXpGa0YwK3VIWEtYWUpwR2w1QzJDUT09',
    'Content-Type': 'application/json'
  },
  data: data
};

And here I am making a Post request

axios(config)
  .then(function (response) {
    console.log(JSON.stringify(response.data));
  })
  .catch(function (error) {
    console.log(error);
  });

我想在Redux Toolkit中发出这种类型的POST请求,尽管我对React Redux有很清楚的了解,并且我在React-Redux中发出了所有类型的REST API请求,但我无法在Redux Toolkit中发出这种POST请求

yi0zb3m4

yi0zb3m41#

我建议使用Redux-toolkit内置的AsyncThunk。注意extraReducers,您可以使用它来处理从服务器返回的响应。
createAsyncThunk:https://redux-toolkit.js.org/api/createAsyncThunk
extraReducers:https://redux-toolkit.js.org/api/createSlice#extrareducers

const postData = createAsyncThunk(
    'postData',
    async (data, thunkAPI) => {

        const config = {
            method: 'post',
            url: '',
            headers: {
                'Authorization': '',
                'Content-Type': ''
            },
            data: data
        };

        const response = await axios(config)
            .then(function (response) {
            console.log(JSON.stringify(response.data));
            })
            .catch(function (error) {
            console.log(error);
            });
        return response.data
    }
)

const initialState = {};

// Then, handle actions in your reducers:
const dataSlice = createSlice({
    name: 'data',
    initialState,
    reducers: {},
    extraReducers: (builder) => {
        // Do something while pending if you want.
        builder.addCase(postData.pending, (state, action) => {})
        // Do something when passes.
        builder.addCase(postData.fulfilled, (state, action) => {})
        // Do something if fails.
        builder.addCase(postData.rejected, (state, action) => {})
    },
})
axr492tv

axr492tv2#

这是更好的选择:

export const authApi = createApi({
  reducerPath: "authApi",
  baseQuery: fetchBaseQuery({
    baseUrl: "https://portalapi.leadsquared.com/api/",
  }),
  endpoints: (builder) => ({
    register: builder.mutation<ResponseData, RequestData>({
      query: (data) => ({
        url: "Authentication/Register?accessKey=u$rab680a72fbd14b1b1cb91a7a91b2c330&secretKey=d39dc85211959db0115594530c07a8268243f937",
        method: "POST",
        body: data,
        headers: {"something":"xxx"},
      }),
    }),
  }),
});

export const { useRegisterMutation } = authApi;

这样使用:

const [register, { isLoading }] = useRegisterMutation();
...
const res = await register(body)

相关问题