对代码转储表示歉意,我不确定如何针对此问题制作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};
}