0
下面的代码缺少适当的关键支撑。本例中我使用Dexie.js。使用React和Dexie指定唯一的密钥ID?
基本上,我有一个自动递增密钥++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/
在循环中使用索引数组。 ejem'return results.map((result,index)=> {return
@RuiCosta使用循环索引作为关键是坏的。 – Alik
@Alik也许。只有当你想更新状态。因为循环不更新,这是有效的。 –