gpt4 book ai didi

javascript - 在组件安装上 react 查询数据库?

转载 作者:行者123 更新时间:2023-12-03 06:24:06 25 4
gpt4 key购买 nike

在这个例子中,我使用 React 和 Dexie.js 。我有一个代码 zanzibar,运行时会将 IndexDB 中的对象列表添加到页面。我现在有两件事想补充一下。

首先,查找我的数据库 ID 似乎存在问题。例如,当我在桃子函数下运行 console.log(amigo.id) 时,它返回 undefined。我在 indexDB 面板上也没有看到 ID。

其次,现在我可以通过点击函数运行它,我还想通过 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/

最佳答案

我不熟悉 Dexie.js,但我想我已经完成了您所要求的任务。

更新的 fiddle :https://jsfiddle.net/jgwhxuam/2/

首先,我将此 block 移至顶部,这样您就不会重复自己(“DRY”)。

var datastoring = new Dexie('MySpace');
datastoring.version(1).stores({friends: '++id, name, age'});
datastoring.open().catch(function(err){ alert('Oh no son:' +err) });

然后,我将您的 getInitialState 结果调整为一个空数组,以便它不会在 dom 上呈现一些空白(带有项目符号等)。

我没有使用控制台将结果记录在 peaches 函数中,而是使用它来获取存储的 indexedDB 数据并将其输入到状态中。我添加了一个 .then() 来完成此任务。当 componentDidMount() 运行时,它应该呈现列表作为结果。

我刚刚稍微整合了 zanzibar 函数并使用桃子函数来更新状态。

我将 renderResults 函数移至 render 函数中。不是必需的,但帮助我调试。

如果您有任何疑问,我可以修改这个答案。祝你好运!

关于javascript - 在组件安装上 react 查询数据库?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38725979/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com