0

我想在我的 action/reducer 切片文件中使用 store 并且我想调用一系列 thunk 来调度 API 响应来存储,以调度下一个 thunk 我需要来自 store 的一些数据我该怎么做?

import { createSlice } from "@reduxjs/toolkit";
import store from '../store'

export const counterSlice = createSlice({
  name: "counter",
  initialState: {
    value: 0,
  },
  reducers: {
    increment: (state) => {
      state.value += 1;
    },
    decrement: (state) => {
      state.value -= 1;
    },
    incrementByAmount: (state, action) => {
      state.value += action.payload;
    },
  },
});

export const { increment, decrement, incrementByAmount } = counterSlice.actions;

export const incrementAsync = (amount) => (dispatch) => {
  setTimeout(() => {
    dispatch(incrementByAmount(amount));
  }, 1000);
};

export const sendIncrementValueToServer= () => (dispatch) => {
  value = store.getState().counter.value //Is this possible to do here?
  const response = //POST API request to send value
};

export const selectCount = (state) => state.counter.value;

export default counterSlice.reducer;
4

1 回答 1

0

Thunks 已经可以getState作为第二个参数访问,因此您只需将其更改为:

// Thunk signature is (dispatch, getState)
export const sendIncrementValueToServer= () => (dispatch, getState) => {
  value = getState().counter.value
  const response = //POST API request to send value
};
于 2020-06-23T23:03:08.763 回答