简体   繁体   中英

reducer method in createSlice (Redux toolkit)

here's the code example in reduxtoolkit Doc:

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

my first question is, why we use reducer method on counterSlice and my second question is, why when we log the store we will get the initial value that we passed (i mean, we were exporting reducer not the initial value but at the end we got the initial value)

i'm new to the concept of redux and reduxtoolkit here in this question i'm getting it wrong the two concepts

in Redux we have only one Reducer and we will do all of our jobs there

but in Redux toolkit we can have more than just one reducer

so instead of writing

const store  = createStore(myReducer , initValue)

we would have

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

and we pass our initial value to our createSlice api

and that's why when you log your store through useSelector you will find your initial value

hope my answer would help you to understand better about redux and redux toolkit:)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM