我试图让错误在3秒后从State数组中删除自己,它有点工作,但由于某种原因,它会跳回去并表现得很奇怪/删除多个1超时完成。(请参阅错误功能组件)。
我使用 React 上下文进行状态管理,并希望我能得到任何帮助。
我将不胜感激任何帮助
你可以在这里实时查看错误:https://codesandbox.io/s/flamboyant-jackson-soutv?file=/src/components/Errors.jsx:558-567
Errors.jsx
import { SiteContext } from "../context/SiteContext";
const Error = props => {
const [siteSettings, setSiteSettings] = useContext(SiteContext);
let errors = siteSettings.errors;
console.log("Errors", errors);
let filteredAry = errors.filter(function(obj) {
return obj.id !== props.id;
});
//removed last id , and filteredArray is where we store the new array
console.log("Filtered array", filteredAry);
//after 3 seconds we should update the old array with the new array
useEffect(() => {
setTimeout(() => {
setSiteSettings(siteSettings => ({
...siteSettings,
errors: filteredAry
}));
}, 3000);
}, []);
return <div className="error">{props.error}</div>;
};
const Errors = () => {
const [site, setSiteSettings] = useContext(SiteContext);
const addError = () => {
//find the latest id
let max = 0;
if (site.errors.length > 0) {
max = Math.max.apply(null, site.errors.map(item => item.id)) + 1;
} else {
max = 1;
}
console.log("Highest id: " + max);
//add new error to the State,
setSiteSettings(site => ({
...site,
errors: [...site.errors, { message: "Some error", id: max }]
}));
};
return (
<div id="errors">
Error page
{site.errors.map((error, i) => {
return <Error id={i} error={error.message} />;
})}
<button onClick={addError}>Add error</button>
</div>
);
};
export default Errors;
慕雪6442864
波斯汪
相关分类