Redux Toolkit 如何确定状态对象上的 属性 名称?

How does Redux Toolkit determine property names on the state object?

import { createSlice } from '@reduxjs/toolkit'

export const countersSlice = createSlice({
    name: 'based? based on what',
    initialState: [0, 0, 0, 0],
    reducers: {
        updateCounter: (state, action) => {
            var id = action.payload.id
            var value = action.payload.value

            state[id] += value
        }
    }
})

export const { updateCounter } = countersSlice.actions

export const selectCount = id => state => state.counter[id]

export default countersSlice.reducer

为什么在 selectCount 行中,我必须使用 state.counter.counter 没有在切片中的其他任何地方被引用?我确实喜欢它 .counter 但我只是想了解它是如何产生 属性.

createSlice 中的 name 属性 由 redux-toolkit 内部使用来为您的操作创建名称。如果名称是 'counter',则 updateCounter 操作将具有 { type: 'counter/updateCounter' }。如果它是 'abc',那么您的操作将有 { type: 'abc/updateCounter' }这个名字无关紧要。只要它与您应用中的任何其他减速器不同,就可以了。

If I change .counter to something else, it breaks the entire project

现在你在谈论别的东西,这就是你如何从你的应用程序的根状态 select 你的数据。

export const selectCount = id => state => state.counter[id]

此 select 或函数假定此切片中的缩减程序将位于根缩减程序的 counter 属性 上。当您将减速器与 configureStorecombineReducers 组合时,此减速器相对于根状态的位置 由 属性 键 确定。

您当前的select或假定您的商店如下所示:

import {configureStore} from '@reduxjs/toolkit';
import counterReducer from './yourReducerFile.js'

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

此 属性 键通常与切片的 name 相匹配,但 没有 匹配.

您可以使用任何 属性 键,只要 selector 函数使用相同的键即可。例如:

export default configureStore({
  reducer: {
    someOtherProperty: counterReducer
  }
});
export const selectCount = id => state => state.someOtherProperty[id]