我试图让错误在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;
App.js
import "./styles.css";
import { SiteProvider } from "./context/SiteContext";
import Errors from "./components/Errors";
export default function App() {
return (
<SiteProvider>
<div className="App">
Errors : <Errors />
</div>
</SiteProvider>
);
}
SiteContext.jsx
export const SiteContext = createContext();
export const SiteProvider = props => {
const [siteSetting, setSiteSetting] = useState({
errors: []
});
return (
<SiteContext.Provider value={[siteSetting, setSiteSetting]}>
{props.children}
</SiteContext.Provider>
);
};
最好的问候,丹尼尔。
您必须清除卸载超时。由于您不清楚,因此每次都声明新的超时。
useEffect(() => {
const id = setTimeout(() => {
setSiteSettings(siteSettings => ({
...siteSettings,
errors: filteredAry
}));
}, 3000);
return () => clearTimeout(id);
}, []);
工作示例:https://codesandbox.io/s/stupefied-minsky-innoo?file=/src/components/Errors.jsx