Skip to content

Commit

Permalink
feat(faq & useapp): add useApp hooks & faq of useSelectorQuery
Browse files Browse the repository at this point in the history
  • Loading branch information
innocces committed Sep 29, 2021
1 parent a22cf12 commit 3e0ebea
Show file tree
Hide file tree
Showing 16 changed files with 195 additions and 3 deletions.
4 changes: 3 additions & 1 deletion .umirc.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,9 @@ export default defineConfig({
favicon: '/image/hook.png',
logo: '/image/logo.png',
outputPath: 'docs-dist',
...(process.env.BUILD_TARGET === 'GH' ? { publicPath: '/taro-hooks/' } : {}),
...(process.env.BUILD_TARGET === 'GH'
? { publicPath: '/taro-hooks/', base: '/taro-hooks' }
: {}),
mode: 'site',
devServer: {
host: '0.0.0.0',
Expand Down
1 change: 1 addition & 0 deletions packages/app/src/app.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ export default {
// env
'pages/useEnv/index',
// basic
'pages/useApp/index',
'pages/useRouter/index',
'pages/usePromise/index',
'pages/useBase64ToArrayBuffer/index',
Expand Down
6 changes: 6 additions & 0 deletions packages/app/src/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,12 @@ class App extends Component {

componentDidCatchError() {}

globalData = {
framework: 'react',
package: 'taro-hooks',
basic: 'taro',
};

// this.props.children 是将要会渲染的页面
render() {
return this.props.children;
Expand Down
4 changes: 4 additions & 0 deletions packages/app/src/constant/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,10 @@ export enum APIChildrenName {

export const ChildrenList: { [_: string]: APIChildrenItem[] } = {
[APIChildrenName.basic]: [
{
id: 'useApp',
name: 'useApp 应用实例',
},
{
id: 'useEvent',
name: 'useEvent 事件中心',
Expand Down
4 changes: 4 additions & 0 deletions packages/app/src/pages/useApp/index.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
export default {
navigationBarTitleText: 'useApp',
enableShareAppMessage: true,
};
56 changes: 56 additions & 0 deletions packages/app/src/pages/useApp/index.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
import React, { useCallback, useEffect } from 'react';
import { AtList, AtListItem, AtMessage, AtNoticebar } from 'taro-ui';
import DocPage from '@components/DocPage';

import { useModal, useApp } from 'taro-hooks';

import MOCK from 'mockjs';

export default () => {
const [appInstance, globalData, setGlobalData] = useApp(true);
const [show] = useModal({
title: 'useApp',
content: '您是否要随机修改当前全局变量',
mask: true,
});

useEffect(() => {
show({
content: `当前获取示例(${
appInstance?.config?.window?.navigationBarTitleText || ''
}): 页面个数(${appInstance?.config?.pages.length || 0})`,
});
}, [show, appInstance]);

const handleItemClick = useCallback(
(key: string) => {
show().then((res: any) => {
if (res.confirm) {
setGlobalData(key, MOCK.mock('@name()'));
}
});
},
[setGlobalData, show],
);

return (
<>
<AtNoticebar marquee>
文档中的用例非完整应用, 可查看h5 或 小程序 demo 查看效果
</AtNoticebar>
<AtMessage />
<DocPage title="useApp 应用实例" panelTitle="useApp">
<AtList>
{Object.entries(globalData).map(([key, value]) => (
<AtListItem
onClick={() => handleItemClick(key)}
key={key}
title={key}
note={JSON.stringify(value)}
/>
))}
</AtList>
</DocPage>
</>
);
};
1 change: 0 additions & 1 deletion packages/app/src/pages/useEnv/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import DocPage from '@components/DocPage';

import { useEnv } from 'taro-hooks';
import Taro, { ENV_TYPE } from '@tarojs/taro';
import 'taro-ui/dist/style/components/icon.scss';

const ENVTYPE = [
['WEAPP', 'WEAPP'],
Expand Down
2 changes: 2 additions & 0 deletions packages/hooks/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
import useEnv from './useEnv';

// basic
import useApp from './useApp';
import useRouter from './useRouter';
import usePromise from './usePromise';
import useBase64ToArrayBuffer from './useBase64ToArrayBuffer';
Expand Down Expand Up @@ -64,6 +65,7 @@ import useMap from './useMap';

export {
useEnv,
useApp,
useLaunchOptions,
useRouter,
usePromise,
Expand Down
48 changes: 48 additions & 0 deletions packages/hooks/src/useApp/index.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
---
title: useApp
nav:
title: Hooks
path: /hooks
order: 2
group:
title: 基础
path: /basic
---

# useApp

获取当前程序的唯一实例以及全局数据

## 何时使用

当需要获取程序实例或操作全局数据时

## API

```jsx | pure
const [appInstance, globalData, setGlobalData] = useApp(allowDefault?: boolean)
```

## 参数

| 参数 | 说明 | 类型 | 默认值 |
| ------------ | --------------------------------------------------------------------------------------------------------- | --------- | ------ |
| allowDefault | 在 App 未定义时返回默认实现。当 App 被调用时,默认实现中定义的属性会被覆盖合并到 App 中。一般用于独立分包 | `Boolean` | - |

## 返回值说明

| 返回值 | 说明 | 类型 |
| ------------- | ---------------------------- | ------------------------------------------------------------------ |
| appInstance | 小程序全局唯一 APP 实例 | `Instance` |
| globalData | 全局数据(须在 app.ts 中定义) | `TRecord` |
| setGlobalData | 动态修改全局数据 | `(key: string, value: unknown) => Promise<General.CallbackResult>` |

## 代码演示

<code src="@pages/useApp" />

## Hook 支持度

| 微信小程序 | H5 | ReactNative |
| :--------: | :-: | :---------: |
| ✔️ | ✔️ | ✔️ |
52 changes: 52 additions & 0 deletions packages/hooks/src/useApp/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
import { useCallback, useEffect, useState, useRef } from 'react';
import { getApp } from '@tarojs/taro';

import { isUndefined } from '../utils/tool';

import type { App, General } from '@tarojs/taro';
import type { TRecord } from '../../typings';

export type TSetGlobalData = (
key: string,
value: unknown,
) => Promise<General.CallbackResult>;

function useApp(
allDefault?: boolean,
): [AppInstance: App, globalData: TRecord, setGlobalData: TSetGlobalData] {
const [globalData, setGlobalData] = useState<TRecord>({});
const appInstance = useRef<App>(
getApp({ allowDefault: Boolean(allDefault) }),
);

useEffect(() => {
if (appInstance.current?.$app) {
setGlobalData(appInstance.current.$app.globalData || {});
}
}, [appInstance]);

const setGlobalDataAsync = useCallback<TSetGlobalData>(
(key, value) => {
return new Promise((resolve, reject) => {
if (isUndefined(key)) {
reject({ errMsg: 'setGlobalData: fail' });
} else {
try {
const prevGlobalData = { ...globalData };
prevGlobalData[key] = value;
appInstance.current.$app.globalData = prevGlobalData;
setGlobalData(prevGlobalData);
resolve({ errMsg: 'setGlobalData: ok' });
} catch (e) {
reject({ errMsg: 'setGlobalData: fail', data: e });
}
}
});
},
[globalData, appInstance],
);

return [appInstance.current, globalData, setGlobalDataAsync];
}

export default useApp;
6 changes: 6 additions & 0 deletions packages/hooks/src/useSelectorQuery/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -118,3 +118,9 @@ getScrollOffset(selector: string).then((offsetInfo: NodesRef.scrollOffsetCallbac
| 微信小程序 | H5 | ReactNative |
| :--------: | :-: | :---------: |
| ✔️ | ✔️ | |

## FAQ

- 为什么获取不到结果, 时有时无?

官方推荐的获取时机为`onReady|useReady`时, 若在`ready`中依然有不稳定因素建议搭配`nextTick`来确保元素已经渲染完成.
3 changes: 3 additions & 0 deletions packages/hooks/src/utils/tool.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,3 +12,6 @@ export const typeOf = (target: any, type: string | string[]): boolean => {

export const isPlainObject = (object: TRecord): boolean =>
!(object && Object.entries(object).length);

export const isUndefined = (target: unknown): boolean =>
typeof target === 'undefined';
2 changes: 1 addition & 1 deletion packages/hooks/tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,6 @@
"extends": "../../tsconfig.json",
"compilerOptions": {
"rootDir": "src",
"typeRoots": ["./typings/*.d.ts", "../../node_modules/@types"]
"typeRoots": ["./typings/index.d.ts", "../../node_modules/@types"]
}
}
4 changes: 4 additions & 0 deletions packages/hooks/typings/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,3 +7,7 @@ interface INavigator extends Navigator {
declare var navigator: INavigator;

declare var wx: any;

declare type TRecord<T = unknown> = {
[_: string | number]: T;
};
1 change: 1 addition & 0 deletions tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
"@@/*": ["src/.umi/*"],
"@components/*": ["packages/app/src/components/*"]
},
"typeRoots": ["node_modules/@types", "typings.d.ts"],
"allowSyntheticDefaultImports": true,
"skipLibCheck": true,
"declaration": false,
Expand Down
4 changes: 4 additions & 0 deletions typings.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,3 +18,7 @@ interface INavigator extends Navigator {
declare var navigator: INavigator;

declare var wx: any;

declare type TRecord<T = unknown> = {
[_: string | number]: T;
};

2 comments on commit 3e0ebea

@vercel
Copy link

@vercel vercel bot commented on 3e0ebea Sep 29, 2021

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Successfully deployed to the following URLs:

taro-hooks – ./

taro-hooks-innocces.vercel.app
taro-hooks-git-main-innocces.vercel.app
taro-hooks-theta.vercel.app

@vercel
Copy link

@vercel vercel bot commented on 3e0ebea Sep 29, 2021

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Successfully deployed to the following URLs:

taro-hooks-h5 – ./

taro-hooks-h5-green.vercel.app
taro-hooks-h5-innocces.vercel.app
taro-hooks-h5-git-main-innocces.vercel.app

Please sign in to comment.