reactjs - 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
,userActions
和initialState
隐含的 'any' 类型。
我现在挣扎了几个小时,却一无所获......任何帮助表示赞赏!
解决方案
实际上,类型很大程度上取决于您如何设计数据结构,这是listeners
类型的一个示例:
let listeners: ((state: typeof globalState) => void)[] = [];
推荐阅读
- .htaccess - 重定向定位到旧网址的开头和结尾
- python - z3py push 后模型错误但没有正确模型
- gson - 如何在 JAVA 中包装改造响应?
- django - 让 django 在 docker-compose 中使用 `network_mode: host`
- cygwin - Q:镜像下载步骤cygwin安装报错怎么处理?
- angular - 无法绑定到“ngForOf”,因为在子模块的组件中访问 *ngFor 时它不是“div”的已知属性
- javascript - 关于 concole.log 中显示错误时的行为
- python - 如何在列表列表中生成随机数
- python - 如何检查处理 Celery 任务的队列
- bash - 用于取消当前(以及所有后续)脚本的 Bash 退出选项