この例では React とDexie.jsを使用しています。コード zanzibar を実行すると、IndexDB からページにオブジェクトのリストが追加されます。これに追加したい現在の2つのことがあります。
まず、データベースの ID の検索に問題があるようです。たとえばconsole.log(amigo.id)
、桃関数の下で実行すると、 が返されますundefined
。indexDB パネルにも ID が表示されません。
次に、クリック関数からこれを実行できるようになったので、indexDB データを 経由でロードしたいと思いますcomponentDidMount
。これの目的は、ページの読み込み時に 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/