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;

這樣就簡單實現了一個跨組件狀態管理的功能

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章