我得到的產品與道具映射到顯示在一個表中,但當我點擊按鈕我無法達到該方法removeProduct(產品)與按鈕內的onClick方法。我發現了一個錯誤,如如下:問題與刪除功能ReactJS:TypeError:無法讀取屬性'removeProduct'未定義
TypeError: Cannot read property 'removeProduct' of undefined
at ProductsDashboard.js:53
at immutable.js:3018
at List.__iterate (immutable.js:2208)
at IndexedIterable.mappedSequence.__iterateUncached (immutable.js:3017)
at seqIterate (immutable.js:606)
at IndexedIterable.IndexedSeq.__iterate (immutable.js:322)
at IndexedIterable.toArray (immutable.js:4260)
at new List (immutable.js:2067)
at reify (immutable.js:3572)
at List.map (immutable.js:4403)
// ProductsDashboard.js
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { loadProducts, removeProduct } from '../../actions/products_actions';
import { bindActionCreators } from 'redux';
class ProductsDashboard extends Component {
componentWillMount() {
this.props.loadProducts();
}
removeProduct(product) {
this.props.removeProduct(product);
}
render() {
if (!this.props.products) {
return <div>Producten worden geladen</div>;
}
return (
<div>
<a href="#/dashboard/products/add" class="btn btn-sm btn-success pull-right" style={{marginBottom: '20px'}}>Product toevoegen</a>
<div style={{marginBottom: '20px'}}>
<input class="form-control" type="text" placeholder="Zoek product" />
</div>
<div class="table-responsive">
<table class="table table-striped table-condensed">
<thead>
<tr>
<td>Id</td>
<td>Barcode</td>
<td>Naam</td>
<td>Omschrijving</td>
<td>Prijs</td>
<td>Volume</td>
<td>Eenheid</td>
</tr>
</thead>
<tbody>
{ this.props.products.map(function(product, index) {
var editUrl = `#/dashboard/products/edit/${product.get('id')}`;
return(
<tr key={index}>
<td>{product.get('id')}</td>
<td>{product.get('barcode')}</td>
<td>{product.get('name')}</td>
<td>{product.get('description')}</td>
<td>{product.get('price')}</td>
<td>{product.get('volume')}</td>
<td>{product.get('unit')}</td>
<td><a href={editUrl} class="btn btn-sm btn-primary">Wijzigen</a></td>
<td><button onClick={ this.removeProduct.bind(null, product) } class="btn btn-sm btn-danger">Verwijderen</button></td>
</tr>
)
})
}
</tbody>
</table>
</div>
</div>
)
}
}
function mapDispatchToPorps(dispatch) {
return bindActionCreators({ loadProducts, removeProduct }, dispatch);
}
function mapStateToProps(state) {
return {
products: state.products.get('products')
}
}
export default connect(mapStateToProps, mapDispatchToPorps)(ProductsDashboard);
感謝那些運作良好!但現在我得到另一個錯誤:未捕獲未捕獲類型錯誤:無法讀取屬性的空洞 在removeProduct – Hans
這是因爲你將'this'綁定到'null':'this.removeProduct.bind(null,product)'。因此,在removeProduct內部訪問'this.props'失敗。相反,保持綁定完好並通過包裝它傳遞'product':'onClick = {()=> this.removeProduct(product)}' – Timo