【发布时间】:2023-02-01 17:10:43
【问题描述】:
我有一个上下文存储,它工作正常。
我写了一个自定义钩子来更轻松地使用该上下文
这是代码:
import { useState, useCallback } from 'react';
import { useStore, useActions, SET } from 'context';
const useContextStore = (key: string): [object | any, Function] => {
const store = useStore();
const action = useActions();
const defaultValues = '';
const [data, setData] = useState<object>(() => {
if (store) {
return store[key];
} else {
return defaultValues;
}
});
const storeData: Function = useCallback(
(payload: object) => {
action({ type: SET, path: key, payload: payload });
setData((prev) => ({ ...prev, ...payload }));
},
[action, key]
);
return [data, storeData];
};
export { useContextStore };
它工作正常,但是当我在其他组件中使用 This hook 时,它们不会在设置新商店时重新呈现
我尝试过的是:替换代码
return [data, storeData];
和
return [store?.[key], storeData];
我的问题解决了,但我真的不知道为什么会这样……
我的自定义 useLocalStorage 挂钩遇到了类似的问题,我对发现问题感到非常沮丧。
【问题讨论】:
标签: javascript reactjs typescript react-hooks react-context