【发布时间】:2025-12-07 11:55:02
【问题描述】:
使用 dexie 的 useLiveQuery 钩子和 react 时出现以下错误。不明白,以下三种情况都不适用。
错误:
application.78bb5802.js:58032 未捕获的错误:无效的挂钩调用。 Hooks 只能在函数组件的 >body 内部调用。这可能是由于以下原因之一:
- 您可能有不匹配的 React 版本和渲染器(例如 React DOM)
- 您可能违反了 Hooks 规则
- 您可能在同一个应用中拥有多个 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({ 标签:
&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