首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何使用store in slice?

如何使用store in slice?
EN

Stack Overflow用户
提问于 2020-06-24 02:50:31
回答 1查看 342关注 0票数 0

我想在我的action/reducer切片文件中使用store,并且我想调用一系列的thunk,这些thunk将API响应分派到store,以调度下一个thunk,我需要从store中获取一些数据,我该怎么做?

代码语言:javascript
运行
复制
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;
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-06-24 07:03:09

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

代码语言:javascript
运行
复制
// Thunk signature is (dispatch, getState)
export const sendIncrementValueToServer= () => (dispatch, getState) => {
  value = getState().counter.value
  const response = //POST API request to send value
};
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/62541805

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档