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也許。只有當你想更新狀態。因爲循環不更新,這是有效的。 –