首页 > 解决方案 > 为什么在反应中删除后组件不重新渲染

问题描述

尝试从列表中删除元素,但即使我正在使用 useEffect,它也不会重新渲染。我的代码是

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

const initialList = [
  {
    id: 'a',
    firstname: 'Robin',
    lastname: 'Wieruch',
    year: 1988,
  },
  {
    id: 'b',
    firstname: 'Dave',
    lastname: 'Davidds',
    year: 1990,
  },
  {
    id: 'c',
    firstname: 'ssh',
    lastname: 'asssss',
    year: 1990,
  },
  {
    id: 'd',
    firstname: 'Asdf',
    lastname: 'we32e',
    year: 1990,
  },
];

export default function App() {
  const [list, setList] = useState(initialList);
  useEffect(() => {
    console.log('useEffect has been called!');
    setList(list);   
  }, [list]);

  const handleRemove = (id,i) => {
    list.splice(i,1)
    setList(list);
  }
  return (
    <div className="App">
    <ul>
      {list.map((item,i) => (
        <li key={item.id}>
          <span>{item.firstname}</span>
          <span>{item.lastname}</span>
          <span>{item.year}</span>
          <button type="button" onClick={() => handleRemove(item.id,i)}>
            Remove
          </button>
        </li>
      ))}
    </ul>
    </div>
  );
}

标签: reactjsreact-hooks

解决方案


在反应中直接修改状态总是一个问题,通常被认为是一种反模式。你可以这样做:

const handleRemove = (id) => {
    const newArr = list.filter((el) => el.id !== id);
    setList(newArr);
  }

而且您也不需要任何东西useEffect,该函数应该处理状态更改。


推荐阅读