首页 > 解决方案 > 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!"
                    })
                }
            })
        }
    }

系统的作用:

  1. 创建用户
  2. 获取用户 ID
  3. 更新部门数组以将用户添加为代理。

我得到的错误是什么:

  1. 每当页面刷新并创建一个新用户时,我都会收到带有 userId 的错误消息,它说该值为 null 并且注册将通过,因为这就是我设计它的方式,它的 id 将显示在控制台选项卡中进行测试,但我'不再能够继续执行第 2 步和第 3 步。
  2. 如果我不刷新页面并再次创建新用户,则会显示其 id 并将继续执行第 2 步和第 3 步,但将从部门文档存储到我的代理数组的 id 是之前生成的 id从上一个用户创建。

请帮忙 :-)

标签: javascriptnode.jsreactjsmongodb

解决方案


有两件事,

  1. 刷新页面实际上应该删除所有反应持有的数据。如果您想在两次刷新之间保留数据,请使用 sessionStorage

  2. 通过 useState 挂钩设置值会在渲染后显示值。因此,您不能setUserId在下一个承诺中执行agentId: userId并期望获得更新的值。您将获得最后一个值。

因此,与其agentId: userId这样做agentId: userData,不如快速解决。


推荐阅读