react useReducer

我们要修改下,将单一组件的状态提取出来,

提取成为全局的组件状态,方便各个组件使用!

为了测试这个东西,我们的设计是这样的,计数器

count 一个组件加,一个组件减

Cart 里面加

这个时候用到了reducer

import React, { useReducer } from 'react'
//此时state 就是 count 
function countReducer(state, action) {
    // 这里写法都是标准写法!
    // 我去上趟茅坑,回头接着写。。。
    // todos ...
    // 接着写,蚊子咬死我了,你知道的,夏天蚊子很多
    switch (action.type) {
        case "add":
            state++;
            return state;
            break;//论理说不会走到该语句,但是你写也没错啊,费代码,增加些数量,
        // 按照代码行数给钱!我发现现在做建筑的都喜欢挖坑,专门赚浮浅,死的快 
        //没有一个做大的!质量不行,把别人当傻子,最后也成为傻子,不扯了,我们继续写我们的代码
        case "minus":
            state--;
            return state;
            break;
        default:
            return state;
    }
}



const Cart = () => {
    const [state, dispatch] = useReducer(countReducer, 0);
    return (
        <div>
            <p> {state} </p>
            <button onClick={() => { dispatch({ type: "add" }) }}>+</button>
            <Hello state={state} dispatch={dispatch}></Hello>
        </div>
    );
};

// hello 里面减少
//hello 组件
const Hello = ({ state, dispatch }) => {
    return (
        <div>
            <p> {state} </p>
            <button onClick={() => { dispatch({ type: "minus" }) }}>-</button>
        </div>
    );
};

export default Cart;

上面代码很简单,但是初学者很容易写错

报如下错误

猜你喜欢

转载自blog.csdn.net/qq_15009739/article/details/107149735