2016-08-04 42 views
0

我的代码被布置的就像这样:使用React从多个文件调用一个变量?

通过datastored变量,它使用INDEXDB包装器Dexie.js main.jsx

var React = require('react'); 
var ReactDOM = require('react-dom'); 
var Console = require('./console.jsx'); 
var Dashboard = require('./dashboard.jsx'); 

var datastored = new Dexie('Notes'); 
datastored.version(1).stores({entries:'++id, title, entry' }); 
datastored.open().catch(function(err){alert("Could not open database:"+err)}); 

main.jsx开机我的数据库。现在,我想从其他文件中调用datastored变量(例如console.jsxdashboard.jsx)。

在我的特殊情况下,我有一个<Addnote/><Dashboard/>。里面有<Addnote/>我有这个功能。

addnote.jsx

sendthru:function(){ 
    var newInput = { 
    title: this.inputTitle.value, 
    entry: this.inputEntry.value  
    }; 
    datastored.entries.add(newInput).then(()=>this.runcheck()); 
    this.inputTitle.value = ''; 
    this.inputEntry.value = '';  
},  

sendthru启动,但是,我的控制台错误指出datastored is not defined。所以我想知道如何让我的整个应用程序调用datastored变量。

回答

2

您可以将数据存储在其他模块中。模块是单身人士,所以你可以创建你自己的文件(例如,storage.js),并在其内部导出一个对象,其中包含你想让其余代码可用的字段。然后,当你在require('./storage')时,你将可以在其他地方访问相同的数据。

+0

所以我假设'main.jsx'看起来像'var datastored = require('./ storage.js')'?然后在storage.js上看起来像'module.exports = new Dexie('Notes');'? –

+0

当然,如果你觉得你需要更多的数据,你可以开始这样做,并改变它 – John

相关问题