0

下面的代码缺少正确的 key 道具。我在这个例子中使用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/

4

1 回答 1

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});
    });
于 2016-08-02T04:18:23.583 回答