出于某种原因,每次从数据库中获取状态后更新状态时,我的整个页面都会重新加载。页面闪烁,我最终到达页面顶部。这是为什么?
我在 sort() 等其他函数中更新了整个状态,无需重新加载即可完美运行。我已将 event.preventDefault() 放入每个点击处理程序中,所以这应该不是问题。
使用 React 的一大优点是无需重新加载即可拥有流畅的 UI,因此这很烦人。
function App() {
const [contacts, setContacts] = useState({ items: [] });
useEffect(() => {
axios
.get('http://localhost:5000/')
.then((result) => {
setContacts({ items: result.data });
})
.catch((err) => console.log(err));
}, []);
这是被调用的函数:
const handleSubmit = (event) => {
event.preventDefault();
if (!id) {
axios
.post('http://localhost:5000/add/', input)
.then(() => {
setInput(emptyState);
})
.catch((err) => console.log(err));
} else {
axios
.post(`http://localhost:5000/update/${id}`, input)
.then(() => {
props.updateContact(input);
setInput(emptyState);
})
.catch((err) => console.log(err));
}
window.location = '/';
};
最佳答案
您需要在 [] 中添加一些内容。 你可以看到我们在第二个参数中将 props.name 传递给了数组。现在,这将导致效果在名称更改时始终再次运行。 如果您不传递任何内容,它将始终更新并且无用。
useEffect(() => {
document.title = `Page of ${props.name}`
}, [props.name])
关于reactjs - 如何阻止 useEffect 每次都重新加载我的页面?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63673526/