2 回答
TA贡献1812条经验 获得超5个赞
您的代码有2个主要问题:
第一:不更新最新状态,并更新差异旧状态
let errors = siteSettings.errors;
console.log("Errors", errors);
// Will provide the old errors, not the updated once
// so each time you add new error, you will get diff filtered array
// for 1 you get 0
// for 2 you get 1
// ....
let filteredAry = errors.filter(function(obj) {
return obj.id !== props.id;
});
useEffect(() => {
setTimeout(() => {
setSiteSettings(siteSettings => ({
...siteSettings,
errors: filteredAry
}));
}, 3000);
}, []);
第二:传递索引,而不是ierror.id
// here you are passing index, instead of error.id
<Error id={i} error={error.message} />;
第一个问题的解决方案是这个做阅读:
useEffect(() => {
const id = setTimeout(() => {
setSiteSettings(siteSettings => {
// get latest copy of state `siteSettings `
// and work on that
let filteredAry = siteSettings.errors.filter(function(obj) {
return obj.id !== props.id;
});
return {
...siteSettings,
errors: filteredAry
}});
}, 3000);
return () => clearTimeout(id);
}, [props.id]);
TA贡献1811条经验 获得超4个赞
您必须在卸载时清除超时。由于你不清楚,所以每次新的超时声明。
useEffect(() => {
const id = setTimeout(() => {
setSiteSettings(siteSettings => ({
...siteSettings,
errors: filteredAry
}));
}, 3000);
return () => clearTimeout(id);
}, []);
您可以像服务一样创建它,可以根据时间戳删除旧的消息:
下面是创建消息时的时间戳。id
片段:
import React, { useState, useEffect } from "react";
import "./styles.css";
const Errors = () => {
const [errors, setErrors] = useState([]);
const [counter, setCounter] = useState(0);
useEffect(() => {
const timerId = setInterval(() => {
if (counter < 10) {
const id = new Date().getTime();
// stop generating
setErrors(ee => ee.concat({ id, message: "Error: " + new Date() }));
}
setCounter(counter + 1);
}, 1000);
return clearInterval.bind(this, timerId);
}, [counter]);
/// clear error
useEffect(() => {
const timerId = setInterval(() => {
setErrors(ee => {
return ee.filter(({ id }) => new Date().getTime() - id < 3000);
});
}, 2000);
return clearInterval.bind(this, timerId);
}, []);
return (
<ul>
{errors.map(({ id, message }, i) => {
return <li key={id}>{message}</li>;
})}
</ul>
);
};
export default function App() {
return (
<div className="App">
<Errors />
<h2>Start editing to see some magic happen!</h2>
</div>
);
}
请检查粗略样品:
https://codesandbox.io/s/quiet-dream-mzcmm?file=/src/App.js:0-1084
添加回答
举报