Javascript 导入(redux 工具包)

时间:2021-03-28 13:18:17

标签: javascript redux-toolkit

official redux toolkit documentation/tutorial 中,有这个文件 (counterSlice.js)

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
    }
  }
})

// Action creators are generated for each case reducer function
export const { increment, decrement, incrementByAmount } = counterSlice.actions

export default counterSlice.reducer

然后将reducer导入到store中:

import { configureStore } from '@reduxjs/toolkit'
import counterReducer from '../features/counter/counterSlice'

export default configureStore({
  reducer: {
    counter: counterReducer
  }
})

由于我在 counterSlice.js 文件中看不到任何对“counterReducer”的引用,我假设导入中包含“counterReducer”:

import counterReducer from '../features/counter/counterSlice'

是一个仲裁名称,可以是我们选择的任何其他名称,例如:

import counterSliceReducer from '../features/counter/counterSlice'

正确吗?

此外,默认导出中的“reducer”来自哪里?

export default counterSlice.reducer

counterSlice 元素包含 'reducers' 对象,而不是 'reducer'。这是从引擎盖下拉出来的吗?

谢谢

1 个答案:

答案 0 :(得分:1)

如果导入的模块使用 export default xxx 方法导出模块,您可以使用任何名称。

createSlice 将返回一个如下所示的对象:

{
    name : string,
    reducer : ReducerFunction,
    actions : Record<string, ActionCreator>,
    caseReducers: Record<string, CaseReducer>
}

看看this docs

相关问题