增加两个api与React钩子配合的函数,懂的人自然懂

手上在写一个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>
  );
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

闲人老师

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值