![](/img/trans.png)
[英]How to set properly the filtered new list to the set State using react js?
[英]How to set state to filtered item react
我想請教一些幫助。 我是 React 新手,在創建檢查處理程序時遇到了困難。 我需要從狀態中獲取項目並僅對所選項目執行此處理程序。 我認為,在檢查/取消選中復選框時,處理程序應設置狀態 - 檢查所選項目的True / False。 我遇到了如何將狀態設置為所選項目的問題。 我的處理程序對所有項目執行。
import React, { Component, createContext } from "react";
import uuid from "react-uuid";
import { warehouseProducts } from "./data";
const ProductContext = createContext();
class ProductProvider extends Component {
state = {
products: [],
detailProduct: "",
editItem: "",
isDisabled: true,
checked: true,
};
[...]
checkHandler = (id) => {
const product = this.state.products.filter(item => item.id === id);
this.setState(() => {
return { checked:!this.state.checked };
});
}
我應用此 checkHandler 的其他組件:
[...]
<ProductConsumer>
{(value) => (
<>
<td style={{ width: "60px" }}>
<input
type="checkbox"
onChange={()=>value.checkHandler(id)}
defaultChecked={value.checked}
/>
</td>
<td style={{ width: "250px" }}>
<Link to="/products/{id}">
{value.checked ? (
<button
className="View"
onClick={() => value.productDetailHandler(id)}
>
View
</button>
) : (
value.isDisabled
)}
</Link>
像這樣的東西就足夠了。 根據選定的 id 過濾並將選中的值設為 true。
checkHandler = (id) => {
const updatedProducts = this.state.products.map(product => {
if (product.id === id) return { ...product, checked: true };
return { ...product, checked: false};
})
this.setState({ products: updatedProducts });
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.