【发布时间】:2016-12-08 03:15:01
【问题描述】:
对于这个例子,我将 React 与 Dexie.js 一起使用。我有一个代码 zanzibar,它在运行时会将我的 IndexDB 中的对象列表添加到页面中。我有两件事要补充。
首先,查找我的数据库的 ID 似乎存在问题。例如,当我在我的 peaches 函数下运行 console.log(amigo.id) 时,它会返回 undefined。我的 indexDB 面板上也没有看到 ID。
其次,现在我可以通过点击函数运行它,我还想通过componentDidMount 加载我的 indexDB 数据。这样做的目的是在页面加载时将我的 indexDB 上的所有内容加载到我的页面中。我的peaches 函数应该这样做,但我不太确定如何执行。
var SisterChristian = React.createClass({
getInitialState:function(){
return {
results:[{id:'', name:'',age:''}]
}
},
peaches:function(){
var datastoring = new Dexie('MySpace');
datastoring.version(1).stores({
friends: '++id, name, age'
});
datastoring.open().catch(function(err){
alert('Oh no son:' +err);
});
datastoring.friends.each((amigo)=>{
console.log(amigo.id+", "+amigo.name);
});
},
componentDidMount:function(){
return this.peaches();
},
zanzibar:function(){
// don't use document.querySelector(), you should be able to access any of your DOM elements like this
var resname = this.inputNameEl.value;
var resage = this.inputAgeEl.value;
var datastoring = new Dexie('MySpace');
datastoring.version(1).stores({
friends: '++id, name, age'
});
datastoring.open().catch(function(err){
alert('Oh no son:' +err);
});
var newFriend = {
name: resname,
age: resage
};
datastoring.friends.add(newFriend).then((id) => {
// this is how you update the state of the object with new data
var newResults = this.state.results.concat([Object.assign({}, newFriend, { id })]);
this.setState({results: newResults});
});
},
renderResults:function(results) {
return results.map(result => { // this is how you create DOM elements from an array of objects
return <li key={result.id}>{result.name}, {result.age}</li>;
});
},
render:function(){
return (
<div>
<input type="text" id="inputname" ref={el => this.inputNameEl = el} />
<input type="text" id="inputage" ref={el => this.inputAgeEl = el} />
<input type="submit" value="Shipping And Handling" onClick={this.zanzibar}/>
<ul>{this.renderResults(this.state.results)}</ul>
</div>
);
}
});
ReactDOM.render(<SisterChristian/>, document.getElementById('bacon'));
包含在 JSFiddle 中 https://jsfiddle.net/jgwhxuam/
【问题讨论】:
-
您应该查看中继:facebook.github.io/relay。它为每个反应组件获取您需要的所有数据。
标签: javascript reactjs dexie