createSlice中的reducer方法(Redux工具包)

xkrw2x1b  于 2022-11-12  发布在  其他
关注(0)|答案(1)|浏览(184)

下面是reduxtoolkit文档中的代码示例:

import { createSlice } from '@reduxjs/toolkit'

export const counterSlice = createSlice({
  name: 'counter',
  initialState: {
    value: 0,
  },
  reducers: {
    increment: (state) => {
      // Redux Toolkit allows us to write "mutating" logic in reducers. It
      // doesn't actually mutate the state because it uses the immer library,
      // which detects changes to a "draft state" and produces a brand new
      // immutable state based off those changes
      state.value += 1
    },
    decrement: (state) => {
      state.value -= 1
    },
    incrementByAmount: (state, action) => {
      state.value += action.payload
    },
  },
})

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

// The function below is called a thunk and allows us to perform async logic. It
// can be dispatched like a regular action: `dispatch(incrementAsync(10))`. This
// will call the thunk with the `dispatch` function as the first argument. Async
// code can then be executed and other actions can be dispatched
export const incrementAsync = (amount) => (dispatch) => {
  setTimeout(() => {
    dispatch(incrementByAmount(amount))
  }, 1000)
}

// The function below is called a selector and allows us to select a value from
// the state. Selectors can also be defined inline where they're used instead of
// in the slice file. For example: `useSelector((state) => state.counter.value)`
export const selectCount = (state) => state.counter.value

export default counterSlice.reducer

我的第一个问题是,为什么我们在counterSlice上使用reducer方法,我的第二个问题是,为什么当我们记录存储时,我们将获得我们传递的初始值(我的意思是,我们导出的是reducer,而不是初始值,但最终我们获得了初始值)

dgtucam1

dgtucam11#

我对redux和reduxtoolkit这两个概念还不熟悉,在这个问题中,我搞错了这两个概念
Redux中,我们只有一个Reducer,我们将在那里完成所有工作
但在Redux工具包中,我们可以有多个reducer
所以你不用写

const store  = createStore(myReducer , initValue)

我们会

configureStore({
  reducer: {
    counter: counterReducer,
  },
});

并将初始值传递给createSliceapi
这就是为什么当您通过useSelector登录存储时,您会发现初始值
我希望我的回答能帮助您更好地了解Redux和Redux工具包:)

相关问题