简体   繁体   中英

how to delete an image from an array in function component

The handleRemoveImgButn should remove the first image, but when I click the handleRemoveImgButn, the image is not removing from the DOM. I also tried setImgs((prevImgs) => prevImgs.filter(img => prevImgs.indexOf(img),== 0. but it doesn't work. Below is the code. Thanks for any help in advance.

import React, { useState, useEffect } from "react";
import "./styles.css";
import AddImgButn from "./AddImgButn";
import RemoveImgButn from "./RemoveImgButn";

export default function App() {
  const [imgs, setImgs] = useState([]);

  
  const handleAddImgClick = () => {
    fetchId();
  };

  const handleRemoveImgClick = () => {
    setImgs((prevImgs) => prevImgs.splice(1));
  };

  return (
    <>
      <h1>Catt</h1>
      <div>
        <AddImgButn onClick={handleAddImgClick} />
        <RemoveImgButn onClick={handleRemoveImgClick} />
      </div>
      <div>
        {imgs.map((img, i) => (
          <img key={i} src={img} className="cat" alt="cat" />
        ))}
      </div>
    </>
  );
}

This happens because splice changes the old array

Then useEffect does not detect a change between it and the new one

You can use slice instead

 const handleRemoveImgClick = () => {
    setImgs((prevImgs) => prevImgs.slice(1));
  };

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