reactjs - 数据从节点返回时 MERN 堆栈出现问题
问题描述
我正在使用 Fetch API 将数据发布到我的节点服务器。我看到了一些我无法理解的行为,需要一些帮助来解决。当用户单击一个按钮时,会打开一个带有几个字段的表单。在点击提交时,数据被传递到节点服务器。首先,它为 Mongo 创建一条新记录并将数据保存在集合中。保存后,我想从其他几个集合中获取一些数据,然后将信息发送回我的反应应用程序。
这就是我所看到的。
如果我只保存数据而不做获取部分并发回这样的消息
res.status(201).json({"message":"data received"}) 然后在我的控制台中关闭模式后,我看到消息“已接收数据”。
但是,如果我执行 fetch 部分,这基本上意味着多几毫秒的延迟,那么一旦模式关闭,此消息就会在反应控制台中闪烁。
警告:无法对未安装的组件执行 React 状态更新。这是一个空操作,但它表明您的应用程序中存在内存泄漏。要解决此问题,请在 useEffect 清理函数中取消所有订阅和异步任务。DOMException:用户中止了请求。
这是我在反应中的提交处理程序
const submitHandler = async(event) => {
event.preventDefault()
try {
const responseData = await sendRequest('http://localhost:5000/challenge/createChallenge', 'POST',
JSON.stringify({
location: selectedOption,
format: selectedOption1,
date: selectedDate.toString(),
opponent: props.initialValues,
month: cMonth,
year: cYear,
player: auth.profile.MemberName
}),
{
'Content-Type': 'application/json',
Authorization: 'Bearer ' + auth.token
})
console.log(responseData)
} catch (err){
console.log(err)
}
}
这是我的 http-hook,这是我正在使用的自定义钩子
import { useState, useCallback, useRef, useEffect } from 'react'
export const useHttpClient = () => {
const [isLoading, setIsLoading] = useState(false)
const [error, setError] = useState(false)
const activeHttpRequests = useRef([])
const sendRequest = useCallback(async (url, method = 'GET', body = null, headers = {}) => {
setIsLoading(true)
const httpAbortCtrl = new AbortController()
activeHttpRequests.current.push(httpAbortCtrl)
try {
const response = await fetch(url, {
method,
body,
headers,
signal: httpAbortCtrl.signal
})
const responseData = await response.json()
activeHttpRequests.current = activeHttpRequests.current.filter(reqCtrl => reqCtrl !== httpAbortCtrl)
if(!response.ok){
throw new Error(responseData.message)
}
setIsLoading(false)
return responseData
} catch (err){
setError(err.message)
setIsLoading(false)
throw err
}
}, [])
const clearError = () => {
setError(null)
}
useEffect(() => {
return () => {
activeHttpRequests.current.forEach(abortCtrl => abortCtrl.abort())
}
}, [])
return { isLoading, error, sendRequest, clearError}
}
有人可以帮忙吗?我不确定如何解决这个问题。我检查了这个错误的原因,而互联网上的一些内容给了我一些线索。但我还不够清楚,无法解决这个问题。
解决方案
推荐阅读
- windows - 运行 npm install WINDOW 的作业时 c 盘中的 Jenkins mkdir 权限问题
- amazon-web-services - 即使帐户处于生产状态,电子邮件也未在 SES 上验证
- javascript - 如何在没有任何 Oauth 验证的情况下将单个 google 表格单元格值作为变量刮到我的网站?(我正在使用 repl.it)
- sql-server - 对电子邮件创建约束
- elasticsearch - Elasticsearch 整个文档搜索(Smart Search)
- firebase - 有没有办法在 MicrophoneInfo 的帮助下选择特定的麦克风作为 AudioSource 进行音频录制?
- python - 使用 Python 中的 Jack Audio Kit 录制数据
- javascript - Puppeteer 测试对话框/模态输入字段
- c# - jQuery选择所有未回答的多项选择题
- shell - 通过ansible的shell命令中的语法错误