我试图在React中实现一个增量按钮,它将表中字段的值更新为1。
这是我目前正在尝试的:
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
cars: [
{
"manufacturer": "Toyota",
"model": "Rav4",
"year": 2008,
"stock": 3,
"price": 8500
},
{
"manufacturer": "Toyota",
"model": "Camry",
"year": 2009,
"stock": 2,
"price": 6500
},
{
"manufacturer": "Toyota",
"model": "Tacoma",
"year": 2016,
"stock": 1,
"price": 22000
},
{
"manufacturer": "BMW",
"model": "i3",
"year": 2012,
"stock": 5,
"price": 12000
},
{
"manufacturer": "Chevy",
"model": "Malibu",
"year": 2015,
"stock": 2,
"price": 10000
},
{
"manufacturer": "Honda",
"model": "Accord",
"year": 2013,
"stock": 1,
"price": 9000
},
{
"manufacturer": "Hyundai",
"model": "Elantra",
"year": 2013,
"stock": 2,
"price": 7000
},
{
"manufacturer": "Chevy",
"model": "Cruze",
"year": 2012,
"stock": 2,
"price": 5500
},
{
"manufacturer": "Dodge",
"model": "Charger",
"year": 2013,
"stock": 2,
"price": 16000
},
{
"manufacturer": "Ford",
"model": "Mustang",
"year": 2009,
"stock": 1,
"price": 8000
},
]
};
}
onHeaderClick(){
}
increaseStock(event){
this.setState({cars: this.state.cars.stock + 1})
}
decreaseStock(event){
this.setState({cars: this.state.cars.stock + 1})
}
render() {
return (
<table>
<tr>
<th>Manufacturer</th>
<th>Model</th>
<th onClick={()=> this.onHeaderClick}>Year</th>
<th>Stock</th>
<th>Price</th>
<th>Options</th>
<th></th>
</tr>
{
this.state.cars.map(car => (
<tr key={car.model}>
<td>{car.manufacturer}</td>
<td>{car.model}</td>
<td>{car.year}</td>
<td>{car.stock}</td>
<td>${car.price}.00</td>
<td><button type="button" onClick={this.increaseStock.bind(this)}>Increment</button></td>
<td><button type="button" onClick={this.decreaseStock.bind(this)}>Decrement</button></td>
</tr>
))
}
</table>
);
};
}
ReactDOM.render(<App />, document.getElementById("app"))
我已经尝试了一堆不同的实现,都无济于事。我哪里出错了?
4条答案
按热度按时间gjmwrych1#
您正在尝试更新整个数组
cars
(它最终将只是一个数字),而不是特定的car
对象。您应该做的是将当前的
car
作为参数传递到您的函数中,并相应地更新state
方法
dwbf0jvd2#
TLDR;您应该从数组中更新特定汽车的
stock
值,而不是cars
数组本身。This one似乎可以工作。建议:正如ReactJS官方文档中所建议的那样,尝试将其分解为更小的组件。在您的情况下,map函数中的
<tr>
可以很容易地作为一个单独的组件提取出来(例如CarModelItem
)。或者更深入地将按钮提取到一个单独的组件中。在拆分之后,您可以将increaseStock
和increaseStock
作为回调传递给这些组件props。rta7y2nd3#
首先,您需要为每个元素添加一个唯一的id
现在,您必须在数组中找到具有id的元素,然后递增或递减stock
ercv8c1e4#
因为你有一个汽车的数组,你需要找到一种方法来识别哪个型号是要更新的。在这个例子中,我给按钮附加了一个数据属性,这个属性可以在函数中获得。
在类方法中,复制要更新的汽车的汽车state(find the index),增加/减少其库存值,然后更新状态。
注意:最好在构造函数中
bind
你的类方法。第一个