我想在动作/减速器切片文件中使用存储,并想调用将API响应发送到存储中的thunk系列,以分派下一个thunk,我需要存储中的一些数据,我该怎么做?
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;
答案 0 :(得分:0)
暴徒已经可以访问getState
作为第二个参数,因此您只需将其更改为:
// Thunk signature is (dispatch, getState)
export const sendIncrementValueToServer= () => (dispatch, getState) => {
value = getState().counter.value
const response = //POST API request to send value
};