简体   繁体   English

如何在 React 项目中连接 LowDB?

[英]How do I connect LowDB in React project?

First I apologize for my poor English skills.首先,我为我糟糕的英语水平道歉。 I have a question about LowDB.我有一个关于 LowDB 的问题。 There is software that I am developing using React + Electron + LowDB.我正在使用 React + Electron + LowDB 开发一些软件。 But when I tried to use LowDB in my project, there was a problem.但是当我尝试在我的项目中使用 LowDB 时,出现了问题。

lowDB.js低数据库.js

const low = require('lowdb');
const FileSync = require('lowdb/adapters/FileSync');
const adapter = new FileSync('db_data/db.json');
const db = low(adapter);

db.defaults({ data: [] }).write();

class DBHandler {
  constructor() {
    this.db = db;
  }

  insertStudyTime(saveDate, startTime, endTime, restTime) {

  }
}

export default DBHandler;

time.js时间.js

import React, { Component } from 'react';
import { PropTypes } from 'prop-types';
import { confirmAlert } from 'react-confirm-alert';
import 'react-confirm-alert/src/react-confirm-alert.css';
/* lowDB Import */
import DBHandler from '../../lowDB/lowDB';

Imported LowDB as above.如上导入 LowDB。

The problem was that we could see that running lowDB on node in cmd would work fine.问题是我们可以看到在 cmd 中的节点上运行 lowDB 可以正常工作。

However, a Type Error occurs on the graceful-fs library used by lowdb:但是lowdb使用的graceful-fs库出现了Type Error: 类型错误:无法读取 fs.closeSync.toString() 上未定义的属性“toString”

It seems to be a simple problem.这似乎是一个简单的问题。 I think that there is a part that I am missing.我认为我遗漏了一部分。 It is difficult to find the answer even if I go through the process while looking at each process, refer to the README of the LowDB repository,即使我在查看每个过程的过程中也很难找到答案,请参阅LowDB存储库的README,

yarn add lowdb index.js:纱线添加lowdb index.js:

import low from 'lowdb'
import LocalStorage from 'lowdb/adapters/LocalStorage'

const adapter = new LocalStorage('db')
const db = low(adapter)

const Home=(props)=>{
    db.defaults({ users: [], token:'' }).write()
    #init db, use db.defaults.

     then you can set db, and get db.
     db.get('users').push({ username: 'admin' }).write()  #set user's username
     db.set('token','you token').write()
     

     get:
     db.getState().user.username   =>'admin' 
     #or  db.get('user').find('username').value()
     db.getState().token    =>'you token'
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM