如何在切片中使用存储?
How can I use store in slice?
我想在我的 action/reducer 切片文件中使用存储,我想调用一系列 thunk 将 API 响应发送到存储,以发送下一个 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;
Thunks 已经可以访问 getState
作为第二个参数,因此您只需将其更改为:
// Thunk signature is (dispatch, getState)
export const sendIncrementValueToServer= () => (dispatch, getState) => {
value = getState().counter.value
const response = //POST API request to send value
};
我想在我的 action/reducer 切片文件中使用存储,我想调用一系列 thunk 将 API 响应发送到存储,以发送下一个 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;
Thunks 已经可以访问 getState
作为第二个参数,因此您只需将其更改为:
// Thunk signature is (dispatch, getState)
export const sendIncrementValueToServer= () => (dispatch, getState) => {
value = getState().counter.value
const response = //POST API request to send value
};