【问题标题】:Why is the entry in the state deleted?为什么状态中的条目被删除了?
【发布时间】:2022-11-30 21:07:02
【问题描述】:

我试图做一些非常简单的事情,但我不明白为什么它对我不起作用

所以我有一个组件,其中包含有关用户登录的详细信息 我想请求详细信息用户并将它们放在组件中

所以我做了一个 axios.get 到我的后端,我得到了详细信息,将它们设置在状态中,成功地将它们放入组件中,但是当我刷新页面时,我得到的状态是未定义的

我在这里添加代码

import axios from "axios";
import React, { useEffect, useState } from "react";
import { useParams, useNavigate } from 'react-router-dom'
import './account.css'



function Account(props) {

    const [user, setUser] = useState()
    const [currentPass, setCurrentPass] = useState()
    const [newPass, setNewPass] = useState()
    const [confirmPass, setConfirmPass] = useState()



    let navigate = useNavigate();

    useEffect(() => {
        let userArr = []
        try {
            axios.create({ withCredentials: true }).get(`http://127.0.0.1:3000/users/getMe`)
                .then(res => {
                    console.log(res.data.data.user) //object
                    userArr.push(res.data.data.user)
                    console.log(userArr)
                    setUser(userArr)
                    console.log(user)
                })

        } catch (error) {
            console.log(error)
        }
    }, [])

    const updatePassword = async (e) => {
        e.preventDefault()
        try {
            const res = await axios.create({ withCredentials: true }).patch(`http://127.0.0.1:3000/users/updatePassword`, {
                currentPassword: currentPass,
                newPassword: newPass,
                passwordConfirm: confirmPass
            });
            if (!res) {
                return "not work"

            }
            console.log(res.data.data.user)
            navigate("/", { replace: true });
        } catch (error) {
            console.log(error);
        }
    }



    return (
        <div className="account-container" >
            <div className="title-container">
                <p className="title">My Account</p>
            </div>
            <p className="sub-title">User information </p>
            <form className="form-user-information">
                <div className="div-form-user-information">
                    <label className="label-form-user-information">Username</label>
                    <textarea placeholder="Username..." />
                </div>
                <div className="div-form-user-information">
                    <label className="label-form-user-information">ssss</label>
                    <textarea placeholder={user.map(el => {
                        return el.email
                    })} />
                </div>
                <div className="div-form-user-information">
                    <label className="label-form-user-information">First name</label>
                    <textarea placeholder="First name..." />
                </div>
                <div className="div-form-user-information">
                    <label className="label-form-user-information">Last name</label>
                    <textarea placeholder="Last name..." />
                </div>
            </form>
            <div className="buttom-line"></div>
            {/* //////CONTACT INFORMATION////////// */}
            <p className="sub-title-contact">CONTACT INFORMATION </p>
            <form className="form-contact-information">
                <div className="div-form-contact-information">
                    <label className="label-form-contact-information">Full Address</label>
                    <textarea placeholder="Full Address..." />
                </div>
                <div className="div-form-contact-information">
                    <label className="label-form-contact-information">City</label>
                    <textarea placeholder="City..." />
                </div>
                <div className="div-form-contact-information">
                    <label className="label-form-contact-information">Country</label>
                    <textarea placeholder="Country..." />
                </div>
                <div className="div-form-contact-information">
                    <label className="label-form-contact-information">Postal code</label>
                    <textarea placeholder="Postal code..." />
                </div>
            </form>
            <div className="buttom-line-contact"></div>
            {/* //////PASSWORD INFORMATION////////// */}
            <p className="sub-title-password">UPDATE PASSWORD </p>
            <form className="form-password-information">
                <div className="div-form-password-information">
                    <label className="label-form-password-information">Current Password</label>
                    <textarea onChange={(e) => setCurrentPass(e.target.value)} placeholder="Current Password..." />
                </div>
                <div className="div-form-password-information">
                    <label className="label-form-password-information">New Password</label>
                    <textarea onChange={(e) => setNewPass(e.target.value)} placeholder="New Password..." />
                </div>
                <div className="div-form-password-information">
                    <label className="label-form-password-information">Confirm Password</label>
                    <textarea onChange={(e) => setConfirmPass(e.target.value)} placeholder="Confirm Password..." />
                </div>
                <button onClick={(e) => updatePassword(e)} className="btn-update-pass">Update password</button>
            </form>
        </div>
    );
}

export default Account;
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

【问题讨论】:

  • 你怎么知道是undefined?基于setUser之后的console.log?

标签: javascript reactjs


【解决方案1】:

呈现应用程序时可能未填充状态。尝试通过添加一点 loading 系统来等待 axios 请求:

import axios from "axios";
import React, { useEffect, useState } from "react";
import { useParams, useNavigate } from 'react-router-dom'
import './account.css'



function Account(props) {

    const [user, setUser] = useState()
    const [currentPass, setCurrentPass] = useState()
    const [newPass, setNewPass] = useState()
    const [confirmPass, setConfirmPass] = useState()
    const [loading, setLoading] = useState(true) // add this



    let navigate = useNavigate();

    useEffect(() => {
        let userArr = []
        try {
            axios.create({ withCredentials: true }).get(`http://127.0.0.1:3000/users/getMe`)
                .then(res => {
                    console.log(res.data.data.user) //object
                    userArr.push(res.data.data.user)
                    console.log(userArr)
                    setUser(userArr)
                    console.log(user)
                    setLoading(false) // and this
                })

        } catch (error) {
            console.log(error)
        }
    }, [])

    const updatePassword = async (e) => {
        e.preventDefault()
        try {
            const res = await axios.create({ withCredentials: true }).patch(`http://127.0.0.1:3000/users/updatePassword`, {
                currentPassword: currentPass,
                newPassword: newPass,
                passwordConfirm: confirmPass
            });
            if (!res) {
                return "not work"

            }
            console.log(res.data.data.user)
            navigate("/", { replace: true });
        } catch (error) {
            console.log(error);
        }
    }


    if(loading) return <p>loading</p> //and this...
    return (
        <div className="account-container" >
            <div className="title-container">
                <p className="title">My Account</p>
            </div>
            <p className="sub-title">User information </p>
            <form className="form-user-information">
                <div className="div-form-user-information">
                    <label className="label-form-user-information">Username</label>
                    <textarea placeholder="Username..." />
                </div>
                <div className="div-form-user-information">
                    <label className="label-form-user-information">ssss</label>
                    <textarea placeholder={user.map(el => {
                        return el.email
                    })} />
                </div>
                <div className="div-form-user-information">
                    <label className="label-form-user-information">First name</label>
                    <textarea placeholder="First name..." />
                </div>
                <div className="div-form-user-information">
                    <label className="label-form-user-information">Last name</label>
                    <textarea placeholder="Last name..." />
                </div>
            </form>
            <div className="buttom-line"></div>
            {/* //////CONTACT INFORMATION////////// */}
            <p className="sub-title-contact">CONTACT INFORMATION </p>
            <form className="form-contact-information">
                <div className="div-form-contact-information">
                    <label className="label-form-contact-information">Full Address</label>
                    <textarea placeholder="Full Address..." />
                </div>
                <div className="div-form-contact-information">
                    <label className="label-form-contact-information">City</label>
                    <textarea placeholder="City..." />
                </div>
                <div className="div-form-contact-information">
                    <label className="label-form-contact-information">Country</label>
                    <textarea placeholder="Country..." />
                </div>
                <div className="div-form-contact-information">
                    <label className="label-form-contact-information">Postal code</label>
                    <textarea placeholder="Postal code..." />
                </div>
            </form>
            <div className="buttom-line-contact"></div>
            {/* //////PASSWORD INFORMATION////////// */}
            <p className="sub-title-password">UPDATE PASSWORD </p>
            <form className="form-password-information">
                <div className="div-form-password-information">
                    <label className="label-form-password-information">Current Password</label>
                    <textarea onChange={(e) => setCurrentPass(e.target.value)} placeholder="Current Password..." />
                </div>
                <div className="div-form-password-information">
                    <label className="label-form-password-information">New Password</label>
                    <textarea onChange={(e) => setNewPass(e.target.value)} placeholder="New Password..." />
                </div>
                <div className="div-form-password-information">
                    <label className="label-form-password-information">Confirm Password</label>
                    <textarea onChange={(e) => setConfirmPass(e.target.value)} placeholder="Confirm Password..." />
                </div>
                <button onClick={(e) => updatePassword(e)} className="btn-update-pass">Update password</button>
            </form>
        </div>
    );
}

export default Account;
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

【讨论】:

    猜你喜欢
    • 2020-04-05
    • 1970-01-01
    • 1970-01-01
    • 2016-04-06
    • 2022-01-02
    • 1970-01-01
    • 2023-01-14
    • 1970-01-01
    • 2013-07-02
    相关资源
    最近更新 更多