[英]custom hook in react does not rerender child component
我有一个上下文存储,它工作正常。
我写了一个自定义钩子来更轻松地使用该上下文
这是代码:
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 挂钩遇到了类似的问题,我对发现问题感到非常沮丧。
当你在做...prev
时,它应该会抛出错误,因为你不能传播string
。 您的defaultValue
是一个字符串。
您的代码仅在data
为 object 时有效,但实际情况可能并非如此。
另外,尝试更改初始化 state 的方式。
const [data, setData] = useState<object>(() => {
if (store) {
return store[key];
} else {
return defaultValues;
}
});
到
const [data, setData] = useState<object>(store?.[key] || defaultValues)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.