首页 > 解决方案 > React Typescript 中用于自定义全局状态挂钩的显式类型

问题描述

我找到了一个很棒的 React Hook 来管理我的应用程序的全局状态。但是该示例是用 Javascript 编写的,而我正在使用 TypeScript,因此需要隐式设置类型。

这是我的商店.ts:

import { useState, useEffect } from 'react';

let globalState = {};
let listeners = [];
let actions = {};

export const useStore = (shouldListen = true) => {
  const setState = useState(globalState)[1];

  const dispatch = (actionIdentifier, payload) => {
    const newState = actions[actionIdentifier](globalState, payload);
    globalState = { ...globalState, ...newState };

    for (const listener of listeners) {
      listener(globalState);
    }
  };

  useEffect(() => {
    if (shouldListen) {
      listeners.push(setState);
    }

    return () => {
      if (shouldListen) {
        listeners = listeners.filter((li) => li !== setState);
      }
    };
  }, [setState, shouldListen]);

  return [globalState, dispatch];
};

export const initStore = (userActions, initialState) => {
  if (initialState) {
    globalState = { ...globalState, ...initialState };
  }
  actions = { ...actions, ...userActions };
};

这是 position_store.ts,管理元素坐标的更新(作为开始):

import { initStore } from './store';

interface GlobalState {
  position: { x: number; y: number };
}

const configureStore = () => {
  const actions = {
    TOGGLE_FAV: (position: { x: number; y: number }) => {
      return { position: { x: position.x, y: position.y } };
    },
  };
  initStore(actions, {
    position: { x: 0, y: 0 },
  });
};

Typescript 给了我一个错误,因为listeners, actionIdentifier, payload,userActionsinitialState隐含的 'any' 类型。

我现在挣扎了几个小时,却一无所获......任何帮助表示赞赏!

标签: reactjstypescriptreact-hooks

解决方案


实际上,类型很大程度上取决于您如何设计数据结构,这是listeners类型的一个示例:

let listeners: ((state: typeof globalState) => void)[] = [];

推荐阅读