结合 useContext 和 useReducer实现redux状态共享

4个文件:

1.Xxxtext.tsx

2.Main.tsx

3.Child.tsx

4.GrandChild.tsx

3个api:

1.useContext

2.useReducer

3.createContext

1.Context.tsx

//1.Context.tsx

import { createContext } from "react";
interface IContext {
  number: number;
  dispatchNumbner: any;
}
// const Context = createContext(null); // 这样写会报错
export const Context = createContext<IContext>({
  number: 0,
  dispatchNumbner: null,
}); // 这样写不会报错

2.Main.tsx

//2.Main.tsx

import { useReducer } from "react";
import Child from "./Child";

import { Context } from "./Context";

const App = () => {
  const [number, dispatchNumbner] = useReducer((state: any, action: any) => {
    const { payload, name } = action;

    switch (name) {
      case "a":
        return state + 1;
      case "b":
        return state - 1;
      case "c":
        return payload;
    }
    return state;
  }, 0);
  return (
    <div>
      <button onClick={() => dispatchNumbner({ name: "a" })}>增加</button>
      <button onClick={() => dispatchNumbner({ name: "b" })}>减少</button>
      <button onClick={() => dispatchNumbner({ name: "c", payload: 666 })}>
        赋值
      </button>
      <div>{number}</div>
      <Context.Provider value={{ number, dispatchNumbner }}>
        <Child />
        <br />
        {/* <Child2 /> */}
      </Context.Provider>
    </div>
  );
};

export default App;

3.Child.tsx

//3.Child.tsx

import { useContext } from "react";
import GrandChild from "./GrandChild";
import { Context } from "./Context";

const Child = () => {
  const { number, dispatchNumbner } = useContext(Context);
  //   console.log(number);
  return (
    <div>
      <h1>child</h1>
      {number}
      <br />
      <button onClick={() => dispatchNumbner({ name: "b" })}>减少</button>
      <br />

      <GrandChild />
    </div>
  );
};
export default Child;

4.GrandChild.tsx

//4.GrandChild.tsx

import { useContext } from "react";
import { Context } from "./Context";

const Child = () => {
  const { number, dispatchNumbner } = useContext(Context);
  //   console.log(number);
  return (
    <div>
      <h1> child2</h1>
      {number}
      <br />
      <button onClick={() => dispatchNumbner({ name: "b" })}>减少</button>
    </div>
  );
};
export default Child;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值