gpt4 book ai didi

reactjs - Astro : Access nano store hook "useStore" from a *. astro 文件

转载 作者:行者123 更新时间:2023-12-03 08:03:16 25 4
gpt4 key购买 nike

我定义了 nano storesrc/themeStore.ts中:

import { atom } from 'nanostores';
export const theme = atom('blue');

我正在尝试访问 *.astro 文件的 front-matter 中的商店值。

src/pages/samples/[id].astro:

import { useStore } from '@nanostores/react';
import { theme } from '../../themeStore';
const $theme = useStore(theme); // error

以下错误被抛出到终端控制台:

Warning: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
1. You might have mismatching versions of React and the renderer (such as React DOM)
2. You might be breaking the Rules of Hooks
3. You might have more than one copy of React in the same app
See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.
error Cannot read property 'useCallback' of null
Code:
1645 | var dispatcher = resolveDispatcher();
> 1646 | return dispatcher.useCallback(callback, deps);
| ^
1647 | }
1648 | function useMemo(create, deps) {
1649 | var dispatcher = resolveDispatcher();

这是有道理的......我正在尝试运行一个钩子(Hook),但我不在功能组件内。我之前在使用其他 React 项目时也见过这个错误。

一个潜在的解决方案是转换为 jsx 文件,而不是 astro,但这将是我们希望避免的重构。

在 Astro 中使用 React 时,有没有办法从“*.astro”文件访问 Nano 存储?

最佳答案

您可以使用 .get() 在 React 之外读取存储(包括 Astro 组件中):

import { theme } from '../../themeStore';
const themeState = theme.get();

您仍然应该在 React 组件中使用 useStore

关于reactjs - Astro : Access nano store hook "useStore" from a *. astro 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73251951/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com