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 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113
| import React, {useContext, useEffect, useReducer, createContext} from "react"
const store = { user: null, books: null, movies: null }
const reducer = (state, action) => { switch (action.type) { case "setUser": return {...state, user: action.user} case "setBooks": return {...state, books: action.books} case "setMovies": return {...state, movies: action.movies} default: throw new Error("位置类型") } }
const Context = createContext(null)
const DemoContextReducer = () => { const [state, dispatch] = useReducer(reducer, store) return ( <Context.Provider value={{state, dispatch}}> <User/> <Books/> <Movies/> </Context.Provider> ) }
const User = () => { const {state, dispatch} = useContext(Context) useEffect(() => { ajax("/user").then(user => { dispatch({type: "setUser", user}) console.log(user) }) }, []) return ( <> <h3>姓名</h3> {state.user ? <div>{state.user.name}</div> : null} </> ) } const Books = () => { const {state, dispatch} = useContext(Context) useEffect(() => { ajax("/books").then(books => { dispatch({type: "setBooks", books}) }) }, []) return ( <> <h3>书籍</h3> {state.books ? state.books.map(book => (<div key={book.id}>{book.name}</div>)) : null} </> ) } const Movies = () => { const {state, dispatch} = useContext(Context) useEffect(() => { ajax("/movies").then(movies => { dispatch({type: "setMovies", movies: movies}) }) }, []) return ( <div> <h3>电影</h3> {state.movies ? state.movies.map(item => <div key={item.id}>{item.name}</div>) : null} </div> ) }
export default DemoContextReducer
function ajax(path) { return new Promise((resolve, reject) => { setTimeout(() => { if (path === "/user") { resolve({ id: 1, name: "梁又文" }) } else if (path === "/books") { resolve([{ id: 1, name: "我是一本好书" }, { id: 2, name: "我是一本坏书" }]) } else if (path === "/movies") { resolve([{ id: 1, name: "最时间的尽头" }, { id: 2, name: "八百" }]) } }, 3000) }) }
|