import React, { useState, useEffect, useReducer } from 'react'; import { useImmer } from "use-immer" import './App.css'; function reducer(state: { count: number; }, action: { type: any; }) { switch (action.type) { case 'increment': return { count: state.count + 1 }; case 'decrement': return { count: state.count - 1 }; default: throw new Error(); } } function App() { // 定义 const [state, setState] = useImmer({ people: [ { name: '马云', englishName: 'Jack Ma' }, { name: '马化腾', englishName: 'Pony Ma' }, { name: '李彦宏', englishName: 'Robin Li' } ] }) const [num, setNum] = useState(1); const [stateReducer, dispatchReducer] = useReducer(reducer, {count:999}); useEffect(() => { console.log(num); //处理异步数据 }, [num]) useEffect(() => { console.log(state); }, [state.people[2]]) const onClick = () => { setNum((num) => { console.log(num,"点击之前的变化"); //处理异步数据 return num = 2 }) } const onClick1 = () => { setState((state: { people: { name: string; }[]; }) => { state.people[2].name = '陈强' }) console.log(state);//异步 } const onClick2 = () => { dispatchReducer({ type:"increment"}) console.log(stateReducer.count);//异步 } return ( <div className="App"> <h1>我是useReducer----{stateReducer.count}</h1> <h1>{num}</h1> <ul> {state.people.map(item => <li key={item.englishName}>{item.name}</li>)} </ul> <button onClick={onClick}>点击</button> <button onClick={onClick1}>复杂数据处理</button> <button onClick={onClick2}>我要修改stateReducer</button> </div> ); } export default App;