2.15 Reducer配合Context实现共享状态管理
一、Reducer配合Context实现共享状态管理
Reducer可以整合组件的状态更新逻辑。Context可以将信息深入传递给其他组件。可以整合使用他们来共同管理一个复杂页面的状态
更复杂的状态管理,可以使用第三方库:Redux、Mobx、Zustand等
// 兄弟组件 import { useContext } from 'react' import { ListDispatchContext } from './15.0' function ListHead() { const listDispatch = useContext(ListDispatchContext) return ( <> <div>Default Template</div> <input type="text" /> <button onClick={() => listDispatch({ type: 'add' })}>添加</button> </> ) } export default ListHead // 兄弟组件 import { useContext } from 'react' import { ListContext, ListDispatchContext } from './15.0' function ListContent() { const list = useContext(ListContext) const listDispatch = useContext(ListDispatchContext) return ( <> <div>Default Template</div> <ul> {list.map((item) => { return ( <li key={item.id}> {item.text} <button onClick={() => listDispatch({ type: 'edit', id: item.id })} > 编辑 </button> <button onClick={() => listDispatch({ type: 'remove', id: item.id })} > 删除 </button> </li> ) })} </ul> </> ) } export default ListContent // Reducer 与 Context 整合组件 import { useReducer, createContext } from 'react' export const ListContext = createContext() export const ListDispatchContext = createContext() function listReducer(state, action) { switch (action.type) { case 'add': return [...state, { id: 4, text: '444' }] case 'edit': return state.map((item) => { if (item.id === action.id) { return { ...item, text: 'new' + item.text } } else { return item } }) case 'remove': return state.filter((item) => { if (item.id === action.id) { return false } else { return true } }) } } function ListProvider({ children }) { const [list, listDispatch] = useReducer(listReducer, [ { id: 1, text: '111' }, { id: 2, text: '222' }, { id: 3, text: '333' }, ]) return ( <ListContext.Provider value={list}> <ListDispatchContext.Provider value={listDispatch}> {children} </ListDispatchContext.Provider> </ListContext.Provider> ) } export default ListProvider // 统一组件 import ListHead from './15.1' import ListContent from './15.2' import ListProvider from './15.0' function App() { return ( <> <div>Default Template</div> <ListProvider> <ListHead /> <ListContent /> </ListProvider> </> ) } export default App
最后更新于