所以我有一个util.ts文件,我在其中声明了一个可以在多个地方使用的函数。为此,我从Zustand商店访问一个变量和函数。
import useStore from "@/store/useStore";
const { roomState, setRoomState } = useStore()
const utililtyFunctions = {
sha512: (str: string) => {
return crypto.subtle.digest("SHA-512", new TextEncoder().encode(str)).then(buf => {
return Array.prototype.map.call(new Uint8Array(buf), x => (('00' + x.toString(16)).slice(-2))).join('');
});
},
addRoom: (roomState: {
room_no: number;
adult: number;
child: number;
infant: number;
}[], min_inv: number) => {
if (roomState.length < min_inv) {
setRoomState([
...roomState,
{
room_no: roomState.length + 1,
adult: 0,
child: 0,
infant: 0,
},
]);
}
},
}
export default utililtyFunctions;
但我得到以下错误:React Hook "useStore" cannot be called at the top level. React Hooks must be called in a React function component or a custom React Hook function.eslintreact-hooks/rules-of-hooks
请告诉我如何解决这个问题。或者让我知道任何更好的解决方案来实现相同的功能。
1条答案
按热度按时间7lrncoxx1#
下面是一个简化版本的例子从文档:
因此,在您的情况下,更新房间状态的正确方法是
useStore.setState(newState)
或useStore.getState().setRoomState()