2016-08-03 44 views
1

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

使用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/

回答

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/