大佬教程收集整理的这篇文章主要介绍了useEffect 常量 post 请求,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在尝试使用 MongoDB 数据库构建一个简单的待办事项列表 Web 应用程序。我的功能似乎可以正常工作,但是我的 useEffect 钩子不断向服务器发出无限量的发布请求。我很困惑为什么会发生这种情况。
反应代码
useEffect(() => {
const payload = {
roomkey: roomKey
}
async function getTodos() {
const response = await axios({
url: 'http://localhost:4000/API/choresdisplay',method: 'post',data: payload
})
setItems(response.data.items)
}
getTodos();
},[roomKey,items]) // render whenever roomkey changes (page load) or when user
// adds/deletes item
console.log(items)
function addItem() {
/*setItems(prevItems => {
return [...prevItems,inputText];
});*/
const payload = {
item: inputText,roomKey: roomKey
}
async function addTodo() {
const response = await axios({
url: 'http://localhost:4000/API/chores',data: payload
})
}
addTodo()
seTinputText("");
}
服务端
userRouter.post('/chores',function (req,res) {
const roomkey = req.body.roomKey;
const newItem = new tdlmodel({
Item: req.body.item,roomKey: roomkey
});
newItem.save()
})
userRouter.post('/choresdisplay',async function (req,res) {
const roomkey = req.body.roomkey;
console.log(roomkey)
tdlmodel.find({ roomKey: roomkey },await function (err,foundMates) {
console.log(foundMates)
if (err) {
res.send({
token: user_LOGIN_FAIL
})
} else {
console.log(foundMates);
res.send({
token: user_LOGIN_succesS,items: foundMates,})
}
})
})
这是因为您告诉 useEffect
在 items
更改时重新运行,但随后您在 useEffect
本身内更改了它。所以你正在创建一个无限循环。没有这种依赖,你的逻辑似乎很好,所以把它从列表中删除:
....
},[roomKey])
,
当您在 useEffect 中更改状态 (setItems) 并监听同一状态 (items) 的更改时,会导致无限循环。
您需要在调用周围添加条件或更改依赖项数组
以上是大佬教程为你收集整理的useEffect 常量 post 请求全部内容,希望文章能够帮你解决useEffect 常量 post 请求所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。