2016-08-03 98 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/