[英]Keep getting TypeError: Cannot read property 'map' of undefined when I click on checkbox, dont know where the problem is
So I keep getting this error when I click on checkbox and the desired outcome would be once the checkbox is clicked the property of active should change to opposite.因此,当我单击复选框时,我不断收到此错误,并且期望的结果是单击复选框后,active 的属性应更改为相反。 Even If I remove the activeHandler function once i click on checkbox I get the same error but now for the initial mapping of products in tbody
即使我在单击复选框后删除了 activeHandler 函数,我也会收到相同的错误,但现在对于 tbody 中产品的初始映射
const ProductList = props => {
const [products, setProducts] = useState(
[
{
id: 1,
name: 'Product 1',
ean: 242355,
type: 'Food',
weight: 24,
color: 'blue',
active: true,
quantity: 2,
price: 25
},
{
id: 2,
name: 'Product 2',
ean: 57434,
type: 'Food',
weight: 48,
color: 'red',
active: false,
quantity: 5,
price: 12
}
]
);
const activeHandler = productId => {
setProducts(prevState => {
const updatedProducts = prevState.products.map(prod => {
if (prod.id === productId) {
prod.active = !prod.active
}
return prod
})
return {
products: updatedProducts
}
})
}
return (
<div>
<table className="table">
<thead>
<tr>
<th scope="col">Name</th>
<th scope="col">EAN</th>
<th scope="col">Type</th>
<th scope="col">Weight</th>
<th scope="col">Color</th>
<th scope="col">Active</th>
<th></th>
</tr>
</thead>
<tbody>
{products.map(product => (
<tr key={product.id}>
<td>{product.name}</td>
<td>{product.ean}</td>
<td>{product.type}</td>
<td>{product.weight}</td>
<td>{product.color}</td>
<td>
<input type="checkbox" checked={product.active} onChange={() => activeHandler(product.id)} />
</td>
<td>
<button className="btn btn-secondary mr-1" disabled={product.active}>VIEW</button>
<button className="btn btn-primary mr-1" disabled={product.active}>EDIT</button>
<button className="btn btn-danger" disabled={product.active}>DELETE</button>
</td>
</tr>
))
}
</tbody>
</table>
</div>
)
} }
Your prevState
is the actual array in this case, so you should map over it and also return it as the new state and not an object with a products
key:在这种情况下,您的
prevState
是实际数组,因此您应该映射它并将其作为新状态而不是具有products
键的对象返回:
setProducts(prevState => {
const updatedProducts = prevState.map(prod => {
if (prod.id === productId) {
prod.active = !prod.active
}
return prod
})
return updatedProducts
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.