出于某种原因,每次从数据库中获取状态后更新状态时,我的整个页面都会重新加载。页面闪烁,我最终到达页面顶部。这是为什么?
我在 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])
https://stackoverflow.com/questions/63673526/
相关文章:
react-native - 如何使选项卡栏图标的溢出在 React Native 中可点击?
azure-functions - Azure 函数的 ILogger
java - CMAKE-COMPILE 在 hadoop-hdfs-native 客户端中失败
post - ESP32 异步 Web 服务器 POST 方法不起作用
react-native - 在 React Native 中访问 DOM 元素
python - 为什么在 Python 3.x 中的循环中使用 list() 会返回内存错误?
firebase - 在哪里可以找到 Firebase 部署错误日志?