useReducer与useContext实践
Contents
-
思路:
- 父组件:直接引入并使用
ctx.Provider
,为子组件提供useReducer
返回的[state, dispatch]
两个属性 - 子组件:
useContext
使用父组件提供的上下文,并在返回值中取出state
和dispatch
- Store:导出
initState、Context
与Reducers
- 父组件:直接引入并使用
-
代码:
- store/UserContext.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
import { createContext } from "react"; export const userInit = { list: [] }; export const userContext = createContext(null); export const userReducer = (state, action) => { switch (action.type) { case "getList": return { ...state, list: [3, 4, 5] }; case "delete": return { ...state, list: state.list.filter((i, index) => index !== action.index) }; default: return { ...state }; } };
- App.jsx
1 2 3 4 5 6 7 8 9 10 11 12 13
import { useReducer } from "react"; import List from "./components/List"; import { userContext, userInit, userReducer } from "./store/UserContext"; export default function App() { const [state, dispatch] = useReducer(userReducer, userInit); return ( <userContext.Provider value={{ state, dispatch }}> <List /> </userContext.Provider> ); }
- components/List.jsx
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
import { useContext } from "react"; import { userContext } from "../store/UserContext"; const List = () => { const { state, dispatch } = useContext(userContext); const handleOnClick = () => { dispatch({ type: "getList" }); }; const handleDelete = (index) => { dispatch({ type: "delete", index }); }; return ( <> <button onClick={handleOnClick}>获取数据</button> <ul> {state.list.map((i, index) => ( <li key={i}> {i} <a href="/#" onClick={() => handleDelete(index)}> 删除 </a> </li> ))} </ul> </> ); }; export default List;
Author gsemir
LastMod 2022-08-11