reactjs - 为什么在反应中删除后组件不重新渲染
问题描述
尝试从列表中删除元素,但即使我正在使用 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>
);
}
解决方案
在反应中直接修改状态总是一个问题,通常被认为是一种反模式。你可以这样做:
const handleRemove = (id) => {
const newArr = list.filter((el) => el.id !== id);
setList(newArr);
}
而且您也不需要任何东西useEffect
,该函数应该处理状态更改。
推荐阅读
- sql-server - SQL Server:Raiserror 其中@variable = true
- asp.net - Microsoft Graph API 被禁止
- c# - 实体类型“Abc_xyz”不是当前上下文模型的一部分
- compiler-optimization - Watcom 中的 C 优化不佳
- linux - 对于启用 FIPS 的机器 RSA 密钥不起作用
- android - 魅族、OPPO、小米、vivo都可以使用HMS推送通知吗?
- django-models - Django_Model_Queries_Callbacks
- python - 为什么我的 django 表单为错误的模型创建一个新对象
- python-3.x - 读取 pyspark 中的分区蜂巢表而不是镶木地板
- java - 使用单个for循环比较java中同一数组的元素