react 状态管理

srore
index.tsx
import React from 'react';
// 仓库文件桶
import StoreContent from './StoreContent';
import SetDataBtn from './SetDataBtn';
import ShowDataBox from './ShowDataBox';

function Index() {
  return (
    <>
      <StoreContent>
        <SetDataBtn></SetDataBtn>
        <ShowDataBox></ShowDataBox>
      </StoreContent>
    </>
  );
}

export default Index;

  

SetDataBtn.tsx
// An highlighted block

import { useReactContentFun } from './StoreContent';

const  SetDataBtn=()=> {
  const [state, dispatch]= useReactContentFun();
  return (
    <div>
      <button
        onClick={() => {
          dispatch({ type: 'name', name: 'jsonYc' });
        }}
      >
        设置名字
      </button>
      <button
        onClick={() => {
          dispatch({ type: 'age', age: Number(state.age) + 1 });
        }}
      >
        年龄+1
      </button>
      <button
        onClick={() => {
          dispatch({ type: 'age', age: Number(state.age) - 1 });
        }}
      >
        年龄-1
      </button>
      <button
        onClick={() => {
          dispatch({ type: 'sex', sex: state.sex == '女' ? '男' : '女' });
        }}
      >
        性别
      </button>
    </div>
  );
}

export default SetDataBtn;

  

ShowDataBox.tsx

// An highlighted block

import { useReactContentFun } from './StoreContent';

function ShowDataBox() {
  const [state, dispatch] = useReactContentFun();

  return (
    <>
      <div>
        <p>名称:{state.name}</p>
        <p>年龄:{state.age}</p>
        <p>性别:{state.sex}</p>
      </div>
    </>
  );
}

export default ShowDataBox;

  

StoreContent.tsx
import React, { useReducer, useContext } from 'react';
const ReactContent = React.createContext({});
function StoreContent({ children }: any) {
  function reducer(state: any, action: any = {}) {
    let returnObj = {
      ...state,
      [action.type]: action[action.type]
    };
    console.log(122222, returnObj);
    return returnObj;
  }

  const storeObj = {
    name: 'yc',
    age: 20,
    sex: '男'
  };

  const [state, dispatch] = useReducer(reducer, storeObj);
  //制作一个仓库桶 来装需要用到context的组件
  return <ReactContent.Provider value={[state, dispatch]}>{children}</ReactContent.Provider>;
}

export function useReactContentFun():any {
  return useContext(ReactContent);
}

export default StoreContent;

  

posted @ 2023-08-16 10:26  zjxgdq  阅读(8)  评论(0编辑  收藏  举报