javascript 我需要从一个数组中动态删除项目时,值被改变的React

izkcnapc  于 2023-05-21  发布在  Java
关注(0)|答案(2)|浏览(95)

我需要一些帮助从数组中删除值。这是数组

[
    {
        "label": "One",
        "value": "one"
    },
    {
        "label": "Two",
        "value": "two"
    },
    {
        "label": "Three",
        "value": "three"
    },
    {
        "label": "Four",
        "value": "four"
    },
    {
        "label": "Five",
        "value": "five"
    }
]

这是我试过的代码

useEffect(() => {
            let od = [...options?.stockModeList]
            let dc; 

            if (!isNaN(state?.parentVariant)){
                dc = od.splice(options.length - 2, 2);
            } else {
                dc = od.splice(0, 3);
            }

 // and also I tried this as well

if (state?.parentVariant === null){
                dc = od.splice(options.length - 2, 2);
            } else {
                dc = od.splice(0, 3);
            }
            
            // console.log(dc)

    }, [ options?.stockModeList, state?.parentVariant])

当UI改变时,state?.parentVariant变量会动态更新,它通常是一个空值或整数值。所以如果它是null,那么我需要运行第一个语句,如果它是一个整数,那么我需要运行else语句。
但问题是,即使在值被更改后,它也总是留在if语句中。

cl25kdpy

cl25kdpy1#

我创建了一个新的数组作为stockModeOptions来保存更新的数组数据。我写了02个条件来检查它是null还是空字符串。
并且在“OD.splice(OD.长度-2,2)”中也有一个打印错误;我也分析了错误的数据。
而且我每次更新这个useEffect的时候,整个状态也会更新

useEffect(() => {
        let od = [...options?.stockModeList]

        if (state?.parentVariant === '' || state?.parentVariant === null){
            od.splice(od.length - 2, 2);
        } else {
            od.splice(0, 3);
        }

        setOptions((state) =>({
            ...state,
            stockModeOptions : od,
        }))

    }, [state])
svmlkihl

svmlkihl2#

import React, { useState } from 'react';

function MyComponent() {
  const [items, setItems] = useState([{
    "label": "One",
    "value": "one"
}, {
    "label": "One",
    "value": "two"
}, {
    "label": "One",
    "value": "three"
},]); // your arrays item

  const handleValueChange = (index, newValue) => {
    // Create a new array with the updated value
    const updatedItems = [...items];
    updatedItems[index] = newValue;

    // Update the state with the new array
    setItems(updatedItems);
  };

  const handleRemoveItem = (index) => {
    // Create a new array without the item to be removed
    const updatedItems = items.filter((_, i) => i !== index);

    // Update the state with the new array
    setItems(updatedItems);
  };

  return (
    <div>
      {items.map((item, index) => (
        <div key={index}>
          <input
            type="text"
            value={item}
            onChange={(e) => handleValueChange(index, e.target.value)}
          />
          <button onClick={() => handleRemoveItem(index)}>Remove</button>
        </div>
      ))}
    </div>
  );
}

export default MyComponent;

相关问题