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

标签 reactjs store astrojs nanostores

我定义了 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/

相关文章:

javascript - 丑化 css 类名,如 instagram 或 facebook

javascript - 如何为 GatsbyJS 制作仅客户端组件?

javascript - Redux 将商店保存为 React 应用程序上的全局变量

vite - 在 Astro 中将代码捆绑为单独的 js 文件(astro.build、astrojs)

reactjs - 在react-apollo的查询组件中设置状态

javascript - location.state 因 gatsby 构建而失败

javascript - 将数组存储为变量然后转换回数组

c - 如何在 c 中保存递归函数的值?

javascript - 如何在 AstroJS 中使用 SVG?

dynamic-routing - Astro.js 动态路由