【问题标题】:Reactjs delete an item from Dexie.jsReactjs 从 Dexie.js 中删除一个项目
【发布时间】:2016-12-08 13:26:25
【问题描述】:

此示例使用 Reactjs 和 Dexie.js. 我有一个没有 D 的 CRUD 应用程序,我目前需要它。虽然您可以将新项目输入并存储到数据库中,但我不确定如何选择每个已添加的项目并删除它们。我知道您必须通过他们的 ID 选择他们。

我使用 i 标签附加了.onClick={this.removal}。但是,我不确定要向removal 函数添加什么。

 var datastored = new Dexie('MyPlace');
datastored.version(1).stores({entries:'++id, title, entry' });
datastored.open().catch(function(err){alert("Could not open database:"+err)});

var Dashboard = React.createClass({
 getInitialState:function(){
  return {results: [] }
  },

runcheck:function(){
  let arr = [];
  datastored.entries
  .each((uploaded)=>arr.push(uploaded))
  .then(()=>this.setState({results:arr}));    
},   

componentDidMount:function(){
  this.runcheck();
},

removal:function(){
  datastored.entries.delete();    
},    

sendthru:function(){
  var newInput = {
  title: this.inputTitle.value,
  entry: this.inputEntry.value    
  };
  datastored.entries.add(newInput).then(()=>this.runcheck());   
  this.inputTitle.value = '';    
  this.inputEntry.value = '';     
},

renderdem:function(){
   var list = this.state.results.map(result =>{
    return <tr key={result.id}>
        <td>{result.id}</td> 
        <td>{result.title}</td> 
        <td>{result.entry}
        <i className="fa fa-times-circle exout" aria-hidden="true" onClick={this.removal}></i>
        </td>
    </tr>
});       
return (<div>
    <p>Title</p>        
    <input type="text" id="inputname" className="form-control" ref={el => this.inputTitle = el} />
    <p>Entry</p>        
    <textarea id="inputentry" ref={el => this.inputEntry = el} className="form-control"></textarea>
<button className="btn btn-info" onClick={this.sendthru}>Add</button>        
        <table className="table table-bordered"><tbody>{list}</tbody></table>
</div>);   
},    

render:function(){
  return this.renderdem();}        
});

ReactDOM.render(<Dashboard />, document.getElementById('main'));

我已将我的代码包含在 JSFiddle 中

https://jsfiddle.net/5uevnock/

【问题讨论】:

    标签: javascript reactjs dexie


    【解决方案1】:

    正如您所注意到的,您需要传递 id 才能知道要删除的内容。但是,将removal 函数绑定到onClick 时,不能立即删除该条目。这里的技巧是让removal 返回一个在点击发生时会被调用的函数。

    removal:function(id){
      var component = this;
      return function(evt) {
        datastored.entries.delete(id);   
        component.runcheck();
      }
    }
    

    像这样使用它:

    <i className="fa fa-times-circle exout" aria-hidden="true" onClick={this.removal(result.id)}></i>
    

    工作示例:https://jsfiddle.net/LukaszWiktor/u1vfoqgp/

    【讨论】:

      猜你喜欢
      • 2016-06-24
      • 2022-11-30
      • 1970-01-01
      • 1970-01-01
      • 2017-08-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多