使用Dexie useLiveQuery hook报错dexie.liveQuery is not a function
这个问题同时存在版本不兼容和代码编写错误,不是库本身的bug。
核心原因
- 版本匹配问题:dexie-react-hooks v1.0.7要求依赖Dexie v3.1.0及以上版本,你当前使用的Dexie v3.0.3版本未内置
liveQueryAPI,是触发报错的直接原因。 - API调用错误:
useLiveQuery的第一个入参要求是返回查询对象的函数,不能直接传入查询实例,否则即使升级版本也无法正常运行。 - 边界判断缺失:
useLiveQuery在查询完成前会返回undefined,直接调用map方法会触发新的类型错误。
修复步骤
- 升级Dexie到符合要求的版本,执行命令:
npm install dexie@^3.1.0
- 调整组件代码,修改后的完整代码如下:
import React from 'react'; import Dexie from 'dexie' import { useLiveQuery } from 'dexie-react-hooks' const myDb = new Dexie('myTable'); myDb.version(1).stores( { items: "id,name,startDate,endDate" } ) function App() { // 第一个参数改为返回查询的函数 const items = useLiveQuery(() => myDb.items.orderBy('name'), []); // 加边界判断避免空值报错 const itemViews = items?.map(item => { return <div>{item.name}</div> }) return ( <div className="App"> <ul> {itemViews} </ul> </div> ); } export default App;
内容的提问来源于stack exchange,提问作者Brian
相关产品推荐
相关产品推荐

