const { createRoot } = ReactDOM const { useState, useReducer, useEffect } = React const root = createRoot(document.getElementById('app')) function App() { // const [count, setCount] = useState(0) // 搜集所有的操作某一个数据的方案 // 派发其 传入的不同操作类型 调用不同的操作逻辑 const countReducer = (count, { type, payload }) => { console.log('count : ', count) switch (type) { case 'ADD': return count + payload case 'MINUS': return count - payload case 'MUL': return count * payload case 'DIV': return count / payload default: return count; } } /* useReducer 两个函数: reducer 函数 状态的初始值 */ /* useReducer 返回两个值: 状态的值 dispatch 派发器 */ const [count, dispatch] = useReducer(countReducer, 0) // const handleAdd = () => setCount(count + 2) console.log('dispatch : ', dispatch) useEffect(() => { console.log('组件挂载!!!') }, []) /* null undefined [] 其他值回报警 */ return <div> <p>值: {count}</p> <div> <button onClick={() => dispatch({ type: 'ADD', payload: 1 })} >+</button> <button onClick={() => dispatch({ type: 'MINUS', payload: 1 })} >-</button> <button onClick={() => dispatch({ type: 'MUL', payload: 2 })} >*</button> <button onClick={() => dispatch({ type: 'DIV', payload: 3 })} >/</button> </div> </div> } root.render(<App></App>)
标签:count,const,useReducer,dispatch,用法,react,return,type,payload From: https://www.cnblogs.com/rose-sharon/p/18366761