【发布时间】: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