redux 如何访问Zustand商店外的功能组件?

z6psavjg  于 2023-10-19  发布在  其他
关注(0)|答案(1)|浏览(115)

所以我有一个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
请告诉我如何解决这个问题。或者让我知道任何更好的解决方案来实现相同的功能。

7lrncoxx

7lrncoxx1#

下面是一个简化版本的例子从文档:

import { create } from 'zustand'

const useStore = create(() => ({ paw: true, snout: true, fur: true }))

// Getting non-reactive fresh state
const paw = useStore.getState().paw

useStore.setState({ paw: false })
useStore.setState({ snout: false })

// You can of course use the hook as you always would
function Component() {
  const paw = useStore((state) => state.paw)
  // ...
}

因此,在您的情况下,更新房间状态的正确方法是useStore.setState(newState)useStore.getState().setRoomState()

相关问题