【问题标题】:React and dexie: "Invalid hook call" error in functional componentReact 和 dexie:功能组件中出现“无效的钩子调用”错误
【发布时间】:2025-12-07 11:55:02
【问题描述】:

使用 dexie 的 useLiveQuery 钩子和 react 时出现以下错误。不明白,以下三种情况都不适用。

错误:

application.78bb5802.js:58032 未捕获的错误:无效的挂钩调用。 Hooks 只能在函数组件的 >body 内部调用。这可能是由于以下原因之一:

  1. 您可能有不匹配的 React 版本和渲染器(例如 React DOM)
  2. 您可能违反了 Hooks 规则
  3. 您可能在同一个应用中拥有多个 React 副本

组件(Editor.js):

import React, { useState}  from "react";
import Title from './Title'
import Blocks from './Blocks'
import styled from 'styled-components'
import { useLiveQuery } from "dexie-react-hooks";
import db from '../db'

const Editor = () => {
    const [title, setTitle] = useState('');
    console.log("Editor: start - title state: " + title);

    const tag = useLiveQuery(
        () =>
          title
            ? db.tags.where('name').equals(title)
            : db.tags.toCollection().first(),
        [title]
    );
       
    if(!tag) {
        console.log("tag not loaded yet, returning null");
        return null;
    }

    const onTitleChange = (event) => {
        db.tags.where({ name: title }).modify((item) => item.name=event.target.value)
    }
     
    const EditorStyle = styled.section`
        padding: 10px;
        min-width: 400px;
    `;
    console.log("Rendering with title:" + title + " and tag.name: " + tag.name);
    return (
        <EditorStyle>
            <Title 
                onTitleChange={onTitleChange}
                title={tag?.name}
            />
            <Blocks 
                tag={tag?.name}
            />
        </EditorStyle>
    )
}

export default Editor;

数据库(db.js)

db.version(1).stores({ 标签:&amp;name, *tags, 块:tag, content });

数据库预填充了一个值

db.tags.add({name: "首页"});

使用反应 17.0.1。

我做错了什么?

谢谢!

【问题讨论】:

  • 一个问题是 'db.tags.where('name').equals(title)' 行没有返回承诺。添加 '.first()' 使其返回第一个匹配项。不过,这不应该给出反应钩子问题。可能是捆绑问题。您可以尝试在代码沙盒、stackblitz 或类似工具上创建重现吗?
  • 当然,感谢您的帮助,请参阅示例。错误是不同的...codesandbox.io/s/holy-field-1k4l6?file=/src/Editor.js

标签: reactjs react-hooks indexeddb react-functional-component dexie


【解决方案1】:

你现在需要 dexie@>3.1.0-alpha.5 来使用 dexie-react-hooks。

【讨论】:

  • 您好,我使用的是 dexie hooks 版本 3.1.0-alpha.6
  • codesandbox 示例有 dexie@3.0.3 和 dexie-react-hooks@1.0.2。我将 dexie 升级到 3.1.0-alpha.6 并没有收到错误。不过还没有看到任何内容。
  • 如果您仍有问题,请添加其他 cmets。如果是这样,请提供更新的代码框链接和问题说明。
  • 嗨大卫,谢谢,我已经开始了我的项目的新版本,一切都按预期工作。不知道错误来自哪里,但现在已经消失了。感谢您的帮助!
最近更新 更多