【问题标题】:How can I use store in slice?如何在切片中使用存储?
【发布时间】:2020-06-23 18:50:30
【问题描述】:

我想在我的 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;

【问题讨论】:

    标签: redux react-redux redux-toolkit


    【解决方案1】:

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

    // Thunk signature is (dispatch, getState)
    export const sendIncrementValueToServer= () => (dispatch, getState) => {
      value = getState().counter.value
      const response = //POST API request to send value
    };
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-08-18
    • 1970-01-01
    • 2021-08-05
    • 1970-01-01
    • 2021-10-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多