手上在写一个Taro
的项目,使用React
开发,刚重设计了接口的调用方式,解耦接口和界面,使代码写法更加优雅,分享给大家。
// utils/apiHooks
import { useEffect, useState } from "react";
import EventEmitter from "eventemitter3";
const event = new EventEmitter();
const Cache = {};
/**
* 调整钩子数据,并触发更新
* @param {String} key 绑定键
* @param {Function} getFunction 绑定获取函数
*/
export function onGetCache(key, getFunction) {
Object.defineProperty(Cache, key, { get: getFunction, configurable: true });
event.emit(key, Cache[key]);
}
/**
* 订阅钩子数据
* @param {String} key 订阅钩子键
* @returns 钩子值
*/
export function useCacheState(key) {
const [ state, setState ] = useState(Cache[key]);
useEffect(() => {
const callback = () => setState(Cache[key]);
event.on(key, callback);
return () => event.off(key, callback);
}, [ key ]);
return state;
}
例:写一个接口
import { request } from "request";
import { onGetCache } from "utils/apiHooks";
export function login() {
return request({ url: "" }).then((res) => {
onGetCache("userinfo", () => JSON.deepCopy(res));
onGetCache("userinfo.location", () => res?.location);
return res;
});
}
例:写一个界面组件
import { View, Text } from "@tarojs/components";
import { useCacheState } from "utils/apiHooks";
export default function Component() {
// 默认undefined,调用login接口后界面数据自动更新
const userinfo = useCacheState("userinfo");
const location = useCacheState("userinfo.location");
return (
<View>
<View>
<Text>定位:</Text>
<Text>{location}</Text>
</View>
<View>
<Text>用户信息:</Text>
<Text>{JSON.stringify(userinfo)}</Text>
</View>
</View>
);
}