简体   繁体   中英

Splice deleting last element of an array of object in react

I have text fields that are being added dynamically on button click and mapping the items depending on state variable [inputList]. The problem is when I'm trying to delete a field using the splice or filter option it is always deleting the last item but in the console it is showing that it has deleted the specific item that I wanted but in UI it's removing the last field no matter which field I delete. For example, if there are 3 fields named 'A', 'B'& 'C'. If I try to delete B, it is deleting B but not affecting in the UI. In the UI it is showing only the last item is deleted that is C has been deleted but in console B has been deleted.

Here is my code:

                <FormControl style={{ display: "flex", flex: 1 }}>
              <FormGroup>
                {inputList.map((x, i) => {
                  return (
                    <div key={i}>
                      <div className={styles.options}>
                        {!distributePoints ? (
                          <FormControlLabel
                            key={i}
                            value={x.isCorrect}
                            control={<Checkbox />}
                            checked={x.isCorrect}
                            onChange={(e) => handleIsCorrect(e, i)}
                          />
                        ) : (
                          ""
                        )}
                        <div className="editor">
                          <BubbleEditor
                            handleAnswer={handleInputChange}
                            index={i}
                            theme="bubble"
                          />
                        </div>
                        {distributePoints ? (
                          <TextField
                            variant="standard"
                            name="points"
                            InputProps={{
                              disableUnderline: true,
                              type: "number",
                            }}
                            value={x.points}
                            onChange={(e) => handlePointChange(e, i)}
                            className={styles.inputCounter}
                          />
                        ) : (
                          ""
                        )}

                        {inputList.length !== 1 && (
                          <IconButton
                            onClick={() => handleRemoveClick(i)}
                            className={styles.icon}
                          >
                            <DeleteIcon
                              sx={{ fontSize: 24, color: "#3699FF" }}
                            />
                          </IconButton>
                        )}
                      </div>
                      {inputList.length - 1 === i && (
                        <div
                          style={{
                            display: "flex",
                            justifyContent: "space-between",
                          }}
                        >
                          <button
                            onClick={handleAddClick}
                            type="button"
                            className={styles.addButton}
                          >
                            <img src={PlusSign} alt="" /> Add another answer
                          </button>

                          <div className={styles.label}>
                            <Checkbox
                              checked={shuffle}
                              onChange={handleShuffle}
                              style={{ color: "#00A3FF" }}
                            />
                            Shuffle answer
                          </div>
                        </div>
                      )}
                    </div>
                  );
                })}
              </FormGroup>
            </FormControl>

Remove function:

    const handleRemoveClick = (index) => {
    const list = [...inputList];
    list.splice(index, 1);
    setInputList(list);
  };

Add function:

  const handleAddClick = () => {
    setInputList([...inputList, { answer: "", isCorrect: false, points: 0 }]);
  };

State array of object that is being used:

  const [inputList, setInputList] = useState([
    { answer: "", isCorrect: false, points: 0 },
  ]);

While updating a state property, using its previous value, the callback argument should be used.
This is due to the possible asynchronous nature of state updates

var handleRemoveClick = (index)=> {
    setInputList((list)=> (
        list.filter((o,i)=> (index != i))
    );
};

var handleAddClick = ()=> {
    setInputList((list)=> (
        list.concat({answer:'', isCorrect: false, points: 0})
    );
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM