【问题标题】:Javascript imports (redux toolkit)Javascript 导入(redux 工具包)
【发布时间】:2021-06-24 18:04:18
【问题描述】:

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”。这是从引擎盖下拉出来的吗?

谢谢

【问题讨论】:

  • 关于您的最后一点:createSlice() 返回具有reducer 属性的counterSlice 对象,而不是reducers。见this

标签: javascript redux-toolkit


【解决方案1】:

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

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

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

看看this docs

【讨论】:

    【解决方案2】:

    我假设导入中的“counterReducer”:
    import counterReducer from '../features/counter/counterSlice'
    是一个任意名称,可以是我们选择的任何其他名称

    你是对的,它是 ES6 的特性,可以用任何名称导入默认导出。见:MDN Page

    另外,默认导出中的这个“减速器”来自哪里?
    export default counterSlice.reducer
    counterSlice 元素包含“reducers”对象,而不是“reducer”。这是从引擎盖下拉出来的吗?

    createSlice API 以表单形式返回对象:

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

    counterSlice.reducer是reducer函数,需要导出后再传给store。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-08
      • 2020-05-29
      • 2021-01-05
      • 2021-11-28
      • 2021-06-03
      • 2021-03-16
      相关资源
      最近更新 更多