Astro:从 *.astro 文件访问 nano 存储挂钩“useStore”

Jon*_*ink 2 store reactjs astrojs nanostores

我在以下位置定义了一个纳米商店src/themeStore.ts

import { atom } from 'nanostores';
export const theme = atom('blue');
Run Code Online (Sandbox Code Playgroud)

我正在尝试访问文件前面内容中的商店值*.astro

src/pages/samples/[id].astro

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

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

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();
Run Code Online (Sandbox Code Playgroud)

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

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

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

Nic*_*rdy 5

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

import { theme } from '../../themeStore';
const themeState = theme.get();
Run Code Online (Sandbox Code Playgroud)

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