我正在try 理解(低效地)useSelector如何引用存储在Slice中的const count = useSelector((state) => state.counter.value)行的InitialState

参考文档,这里是Slice:

import { createSlice } from '@reduxjs/toolkit'

const initialState = {
  value: 0,
}

export const counterSlice = createSlice({
  name: 'counter',
  initialState,
  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

这是store :

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

export const store = configureStore({
  reducer: {
    counter: counterReducer,
  },
})

在组件计数器中,我正在try 访问InitialState:

...
export function Counter() {
  const count = useSelector((state) => state.counter.value)
  const dispatch = useDispatch()

  return (
    <div>
     ...
    </div>
  )
}

那么,如果在CounterSlice中默认只导出Reducer对象,Const count=useSelector((State)=&gt;state.Counter.value)如何引用Slice的InitialState呢?

export default counterSlice.reducer

推荐答案

导出的reducer对象与您提供给createSlicereducers属性不同.函数createSlice在幕后发挥了很多魔力,你可以在这里阅读更多RTK的源代码: createSlicecreateReducer.

TL;DR: createSlice将提供的initialState传递给函数createReducer,如下所示:

createReducer(options.initialState, (builder) => {
  // Some code
}

然后createReducerinitialState连接到reduce,如下所示:

if (isStateFunction(initialState)) {
  getInitialState = () => freezeDraftable(initialState())
} else {
  const frozenInitialState = freezeDraftable(initialState)
  getInitialState = () => frozenInitialState
}

// Some code

reducer.getInitialState = getInitialState

有了这一点,store就可以得到initialState.

Reactjs相关问答推荐

无法在jest中发布行动

CreateBrowserRouter将props 传递给父组件以验证权限

如何使用next.js以DOM为目标在映射中使用Ref

有没有办法将在服务器端全局获取的一些数据传递到Next&>13应用程序目录中的客户端组件?

Reaction-Query&-使用Mutation触发成功,而应该触发错误

不同步渲染

同一文件中前端和后端的Nginx配置

如何使用react-router-dom保护嵌套在受保护路由中的嵌套路由?

React-apexcharts 中的 Y 轴刻度不会动态更新符号

如何测试根据 prop 更改 CSS 属性的 useEffect 钩子?

画布:用鼠标绘制形状时重新绘制整个画布会导致卡顿

React 测试库包装器组件

React - 拖放 UML

带有 webpack 错误多个文件匹配路由名称的 Expo-router.无法Bundle 或部署应用程序

React Three Fiber mesh 标签在此浏览器中无法识别

next js 13 在获取中使用标头时动态渲染而不是静态渲染?

如何通过单击多个选项中的特定项目在模态上呈现不同的标题?

使用 react-router-dom 时弹出空白页面

使用 React、Redux 和 Firebase 的无限循环

如何跟踪 dexie UseLiveQuery 是否完成