React Hooks简易实现redux状态管理

React Hook中提供的 useContextuseReducer 以及 context API可以实现类redux的状态管理功能,具体API的使用方法见官方文档,这里结合 TypeScript 演示如何进行组件的状态管理

首先创建共享数据的Store组件 BgStore.tsx

import * as React from 'react';

interface IState {
      // 共享数据结构
  background: string;
}

interface IAction {
      // dispatch派发的action结构
  type: string;
  value: string;
}

export interface IStore {
      // 由React.createContext所创建的store的数据机构,这里与BgContext.Provider 组件上的 value 是相对应的
  state: {
     
    background: string
  };
  dispatch?: React.Dispatch<IAction>;
}

export const BgContext = React.createContext<IStore>({
     
  state: {
     
    background: '#eee'
  }
});


const reducer: React.Reducer<IState, IAction> = (state, action) => {
     
  switch (action.type) {
     
    case 'UPDATE_BG':
      return {
     ...state, background: action.value};
    default:
      return state;
  }
};

export const BgSore: React.FC = ({
     children}) => {
     
  const [state, dispatch] = React.useReducer(reducer, {
     background: '#eee'}); // 创建reducer
  return (
    <BgContext.Provider value={
     {
     state, dispatch}}>
      {
     children}
    </BgContext.Provider>
  );
};

建立根视图 Index.tsx

import * as React from 'react';
import {
      BgSore } from './store/BgStore';
import Content from './components/Content';
import Buttons from './components/Buttons';
import GetState from './components/GetState'; // class component

const MokeRedux: React.FC= () => {
     
  return (
    <BgSore>
      <Content />
      <Buttons />
      <GetState />
    </BgSore>
  );
};

export default MokeRedux;

建立子组件 Content.tsx

import * as React from 'react';
import {
      BgContext, IStore } from '../store/BgStore';

const Content: React.FC = () => {
     
  const store: IStore = React.useContext(BgContext); // 通过useContext获取共享的信息
  return (
    <div style={
     store.state}>background: {
     store.state.background}</div>
  );
};

export default Content;

建立操作背景颜色变换的子组件 Buttons.tsx

import * as React from 'react';
import {
      Button } from 'antd';
import {
      BgContext, IStore } from '../store/BgStore';

const Buttons: React.FC = () => {
     
  const store: IStore = React.useContext(BgContext);

  const handleClickBlue = () => {
     
    store.dispatch!({
      // 这里推断dispatch是一定存在的,因为在 BgContext.Provider 组件中的 value={
     {state, dispatch}}>
    // 之所以添加感叹号是因为在IStore接口中,将dispatch设置为了可选属性
      type: 'UPDATE_BG',
      value: 'blue'
    });
  };

  const handleClickOrange = () => {
     
    store.dispatch!({
     
      type: 'UPDATE_BG',
      value: 'orange'
    });
  };

  return (
    <>
      <Button type="primary" onClick={
     handleClickBlue}>Update blue</Button>
      <Button type="primary" onClick={
     handleClickOrange}>Update orange</Button>
    </>
  );
};

export default Buttons;

class component获取共享数据 GetState.tsx

import * as React from 'react';
import {
      BgContext, IStore} from '../store/BgStore';

interface IState {
     
  name: string;
}

class GetState extends React.Component<{
     }, IState> {
     
  public state = {
     
    name: 'test'
  };

  public render() {
     
    return (
      <BgContext.Consumer>
        {
     (props: IStore) => {
     
          return (
            <div>
              <p>{
     props.state.background}</p>
              <span>{
     this.state.name}</span>
            </div>
          );
        }}
      </BgContext.Consumer>
    )
  }
}

export default GetState;

这样就简单实现了一个跨组件状态管理的功能

你可能感兴趣的:(React,Typescript,React,React,Hooks,TypeScript,Redux,状态管理)