React自定义全局状态钩子的类型

时间:2020-06-25 09:58:52

标签: reactjs typescript

对代码转储表示歉意,我不确定如何针对此问题制作MWE。我正在尝试使用React钩子和Typescript来实现类似Redux的全局状态管理器;基于M. Schwarzmuller在其Udemy React课程中的javascript实现。

问题是我不明白如何正确地键入下面用Vanilla JS编写的这三个“初始化程序对象”:

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

globalState对象应该包含所有状态,listeners数组是全局状态的数组,actions对象应该可以与dispatch函数一起调用(两个)参数。下面是我尝试键入三个“初始化程序”的尝试。这不会在此文件中显示错误消息,但是会在例如调用时

dispatch({actionIdentifier: "GET_USERS", payload: users}); 

从另一个文件中,我收到This expression is not callable. Type '{}' has no call signatures.错误。我确实知道空对象没有呼叫签名。

如何正确键入globalState对象?

import {useState, useEffect } from 'react';

let  globalState: ObjectType = {}
let listeners: Array<Listener>  = [];
let actions: ObjectType = {}; 

interface ObjectType {
    [key:string]:  any;
    // actionIdentifier: string 
};

interface Listener {
    (argument: any): void
};

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

   const dispatch = (actionIdentifier: string, payload: any) => {
       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 initializeStore = (userActions: ObjectType, initialState: ObjectType) => {
    if (initialState) {
        globalState = {...globalState, ...initialState};
    }
    actions = {...actions, ...userActions};
}

0 个答案:

没有答案