javascript - JavaScript/MongoDb:useState 初始注册时出现空值问题
问题描述
我遇到了 useState() 的问题。问题是每当页面刷新 userId 没有值时,因为我设置了它,但在我的代码中我获得了它的值。
const [userId, setUserId] = useState("");
function registerUser(e){
e.stopPropagation();
e.preventDefault();
if (isAdmin == "select permission" || isAdmin == null || isAdmin == undefined || isAdmin == "") {
Swal.fire({
icon: "warning",
title: "Error message!",
text: "Please select a permission to proceed!"
})
} else if(department == "select department" || department == null || department == undefined || department == "") {
Swal.fire({
icon: "warning",
title: "Error message!",
text: "Please select a department to proceed!"
})
} else if(position == "select position" || position == null || position == undefined || position == "") {
Swal.fire({
icon: "warning",
title: "Error message!",
text: "Please select a position to proceed!"
})
} else {
fetch('http://localhost:4000/api/users/email-exist', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
// API only accepts
body: JSON.stringify({
email: email
})
}).then(res => {
return res.json()
}).then(gatheredData => {
if (gatheredData === false) {
fetch('http://localhost:4000/api/users/register',{
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
firstName: firstName,
lastName: lastName,
department: department,
position: position,
email: email,
mobileNo: mobileNo,
isAdmin: isAdmin,
password: "password123",
departmentId: departmentId
})
}).then(res => res.json()).then(convertedData => {
if(convertedData === true){
fetch('http://localhost:4000/api/users/get-id',{
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
email: email
})
}).then(res => res.json()).then(userData => {
setUserId("");
console.log(userData)
setUserId(userData);
console.log(departmentId)
if(userData === "" || userData === undefined) {
alert("Error")
} else {
fetch(`http://localhost:4000/api/users/enroll/${departmentId}`,{
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
agentId: userId
})
}).then(res => res.json()).then(enrolled => {
console.log(enrolled)
if (enrolled === true) {
Swal.fire({
icon: "success",
title: "Congratulations!",
text: "Account has been created successfully."
})
} else {
Swal.fire({
icon: "success",
title: "Warning!!",
text: "Account has been created but not linked to any departments."
})
}
})
}
})
} else {
Swal.fire({
icon: "error",
title: "Error message!",
text: "Something went wrong, please try again later."
})
}
})
} else {
Swal.fire({
icon: "warning",
title: "Error message!",
text: "Email address has already been used!"
})
}
})
}
}
系统的作用:
- 创建用户
- 获取用户 ID
- 更新部门数组以将用户添加为代理。
我得到的错误是什么:
- 每当页面刷新并创建一个新用户时,我都会收到带有 userId 的错误消息,它说该值为 null 并且注册将通过,因为这就是我设计它的方式,它的 id 将显示在控制台选项卡中进行测试,但我'不再能够继续执行第 2 步和第 3 步。
- 如果我不刷新页面并再次创建新用户,则会显示其 id 并将继续执行第 2 步和第 3 步,但将从部门文档存储到我的代理数组的 id 是之前生成的 id从上一个用户创建。
请帮忙 :-)
解决方案
有两件事,
刷新页面实际上应该删除所有反应持有的数据。如果您想在两次刷新之间保留数据,请使用 sessionStorage
通过 useState 挂钩设置值会在渲染后显示值。因此,您不能
setUserId
在下一个承诺中执行agentId: userId
并期望获得更新的值。您将获得最后一个值。
因此,与其agentId: userId
这样做agentId: userData
,不如快速解决。
推荐阅读
- spring-boot - Spring Boot 和 spring-security-jwt 的依赖项
- reactjs - “AnyReactComponent”有什么作用?
- django - 如何用 Django 和 Celery 记录所有任务信息?
- lua - Mouse cylinder behaviour (dual-screen config)
- javascript - 如何在迭代到下一个循环之前等待每个内部完成?
- node.js - 如何在 NodeJS 服务器上使用 mongoose 同步查询
- javascript - Importing JavaScript files in Typescript, unable to access functions in TS, able to access them in html
- dart - Flutter 返回首页
- c# - ASP.Net Core: keep windows authentication
- java - JVM G1 FinalReference 很多时间