如何从反应钩中的数组中删除对象

时间:2021-07-02 17:07:50

标签: javascript arrays reactjs typescript react-hooks

我有一个按钮列表,它们是多选的。当我选择我想添加的按钮时,它会被完美地添加到数组中并变成蓝色,当我点击一个已经选择的按钮时,它应该从数组中移除并变成白色,但它没有。下面显示了我到目前为止的尝试。

第一个数组(products)是保存API数据。第二个是保存选择的产品。

const [products, setProducts] = useState([]);
const [selectedProducts, setselectedProducts] = useState<any>([]);
{products.length !== 0 ? (
    products?.map(
        (item: any, index) => (
            <SButton
                key={item.key}
                label={item.value}
                onClick={() => {
                    selectedProducts(item);
                }}
                isSelected={item.selected === "YES"}
            />
        )
    )
) : (
    <p>No products</p>
)}
function selectedProducts(item:any){
    if(selectedProducts.length !== 0){
        selectedProducts.map((selecteditem:any)=>{
            if(selecteditem.key == item.key ){
                item.selected = "NO";
                setselectedProducts(selectedProducts.filter((item: any )=> item.key !== selecteditem.key))
            }else{
                item.selected = "YES";
                setselectedProducts([...selectedProducts, item]);
            }
        })
    }else{
        setselectedProducts([...selectedProducts, item]);
        item.selected = "YES";
    }
}

3 个答案:

答案 0 :(得分:1)

这样的事情怎么样?

const [products, setProducts] = useState([]);
const [selectedProduct, setSelectedProduct] = useState();

{(products.length > 0) ? (
 <Fragment>
   {products.map((item)=>{
     const {key, value, selected } = item;
     return (
       <SButton
        key={key}
        label={value}
        onClick={() => {
          setSelectedProduct(item);
          const newState = !selected;
          products.forEach((p)=>{
            if (p.key === item.key) p.selected = newState;
          });
          setProducts([...products]);
        }}
        isSelected={selected}
       />
     );
   })}
 </Fragment>
): (
 <p>No products</p>
)}

答案 1 :(得分:1)

首先,您使用 selectedProducts 作为函数名称和所选产品状态的名称。

其次,您不应为 item 赋值。请改用展开运算符。

此外,您可以从 setState 访问之前的状态,而不是直接使用状态。

function removeFromSelectedProducts(item: any) {
    // Set selected to 'NO' in products array
    setProducts((prevProducts) =>
        prevProducts.filter((product) =>
            product.key === item.key ? { ...product, selected: 'NO' } : product
        )
    )
    // Remove product from selectedProducts
    setSelectedProducts((prevSelectedProducts) =>
        prevSelectedProducts.filter((product) => product.key !== item.key)
    )
}

function addToSelectedProducts(item: any) {
    // Set selected to 'YES' in products array
    setProducts((prevProducts) =>
        prevProducts.filter((product) =>
            product.key === item.key ? { ...product, selected: 'YES' } : product
        )
    )
    // Add item to selectedProducts
    setSelectedProducts((prevSelectedProducts) => [...prevSelectedProducts, { ...item, selected: 'YES'}])
 }


function selectProduct(item: any) => {
    if (selectedProducts.some((product) => product.key === item.key)) {
        removeFromSelectedProducts(item)
    } else {
        addToSelectedProducts(item)
    }
}

答案 2 :(得分:0)

您可以使用 useReducer 钩子简化此操作,而不是使用单独的函数来添加和删除所选产品。