小编Lul*_*zim的帖子

如何使用 Context API 在 React 中组合多个 reducer

在 React 应用程序中工作,我目前使用单个减速器定义了一些全局状态,但由于应用程序有点大,所以想引入多个减速器,因此在多个减速器上组织状态会更容易和更好!

目前我有:

import { StoreProvider } from './store'
const app = (
  <StoreProvider>
    <App />
  </StoreProvider>
)
Run Code Online (Sandbox Code Playgroud)

商店看起来像:

import React, { useReducer, createContext } from 'react'
import { ApplicantState } from './interfaces/ApplicantState'
import applicantReducer from './modules/Applicant/ApplicantReducer'

const initialState: ApplicantState = {
  applicants: [],
  total: 0,
}

export const GlobalStore = createContext<ApplicantState | any>(initialState)
export const StoreProvider = ({ children }: JSX.ElementChildrenAttribute): JSX.Element => {
  const [state, dispatch] = useReducer(applicantReducer, initialState)
  return <GlobalStore.Provider value={{ state, dispatch }}>{children}</GlobalStore.Provider>
}
Run Code Online (Sandbox Code Playgroud)

我想要另一个减速器,对于前 …

javascript reactjs context-api

5
推荐指数
0
解决办法
2390
查看次数

标签 统计

context-api ×1

javascript ×1

reactjs ×1