以下代码缺少适当的关键支柱。我在这个例子中使用Dexie.js。
基本上,我有++id
的自动递增键。现在,我想确保我的var newFriend自动递增,但我不确定如何正确指定它。它旨在用于li key={result.id}
。
结果错误为child keys must be unique; when two children share a key, only the first child will be used.
我想将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/
答案 0 :(得分:3)
Dexie自动为每个项目生成唯一ID(模式中的“++ id”)。 Dexie在每次.add()操作后返回一个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});
});