gpt4 book ai didi

javascript - 使用 React 和 Dexie 分配唯一的 key ID?

转载 作者:行者123 更新时间:2023-11-28 18:28:04 24 4
gpt4 key购买 nike

下面的代码缺少正确的 key 属性。我正在使用Dexie.js对于这个例子。

基本上,我有一个带有 ++id 的自动递增键。现在,我想确保我的 var newFriend 自动递增它,但我不确定如何正确指定它。它旨在用于 li key={result.id} 中。

产生的错误是子键必须是唯一的;当两个 child 共享一把 key 时,只有第一个 child 会被使用。

我想设置var newFriend来自动递增我的ID。

不要介意评论标签。他们对我之前提出的问题很感兴趣。

var SisterChristian = React.createClass({
getInitialState:function(){
return {results:[
{id:'', name:'',age:''}
]}
},

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);
});

// you can't do this, you need to add a new item to the results array, not reset the array
// datastoring.friends.each((friend)=>{
// this.setState({results:[{name:resname, age:resage}] });
// });

var newFriend = {
id:,
name: resname,
age: resage
};

datastoring.friends.add(newFriend);

// this is how you update the state of the object with new data
var newResults = this.state.results.slice(); // clone the array
newResults.push(newFriend);
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/7xet1nv0/1/

最佳答案

Dexie 自动为每个项目生成一个唯一的 ID(架构中的“++id”)。 Dexie 在每个 .add() 操作后返回一个 promise 。当 promise 履行时,您可以检索 Dexie 分配的唯一 id,并使用它( demo ):

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 })]); // add the id to the newFriend object, and then concat it to the all state to get a new array
this.setState({results: newResults});
});

关于javascript - 使用 React 和 Dexie 分配唯一的 key ID?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38711219/

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