【问题标题】:How to remove a object from an array in react hook如何在反应钩子中从数组中删除对象
【发布时间】:2021-09-14 15:11:02
【问题描述】:

我有一个按钮列表,它们是多选的。当我选择要添加的按钮时,它将完美地添加到数组中并变为蓝色,当我单击已选择的按钮时,它应该从数组中删除并变为白色,但事实并非如此。下面显示了我到目前为止所做的尝试。

第一个数组(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";
    }
}

【问题讨论】:

  • 使用 arr.splice() 方法从 selectedProducts 中删除产品,如果该项目已被选中...如果您需要进一步的帮助,请提供代码 sn-p 或 codepen 或任何在线 ide喜欢

标签: javascript arrays reactjs typescript react-hooks


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    首先,您将 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)
        }
    }
    

    【讨论】:

      【解决方案3】:

      这样的事情怎么样?

      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>
      )}
      

      【讨论】:

        猜你喜欢
        • 2022-09-29
        • 1970-01-01
        • 2023-03-13
        • 2019-12-11
        • 1970-01-01
        • 1970-01-01
        • 2020-07-13
        • 2021-01-21
        • 1970-01-01
        相关资源
        最近更新 更多