react useContext createContext 方法使用

还是上一篇的例子,我把 代码改下

import React, { useReducer } from 'react'
import { useContext } from "react"

// 创建上下文
const Context = React.createContext();
//此时state 就是 count 
function countReducer(state, action) {

    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 (
        <Context.Provider value={
   
   { state, dispatch }}>
            <div>
                <p> {state} </p>
                <button onClick={() => { dispatch({ type: "add" }) }}>+</button>
                {/* 这一块呢,我不想传递这些值 */}
                <Hello ></Hello>
            </div>
        </Context.Provider>
    );
};

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

export default Cart;

猜你喜欢

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