react useReducer 的基本用法

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>)

  

posted @ 2024-08-19 09:55  小小黑加白  阅读(5)  评论(0编辑  收藏  举报