开发者问题收集

发送到子组件时反应未定义的属性

2022-09-02
877

我想将登录用户对象发送到个人资料页面以编辑和上传图像,但最终出现错误“ProfileImage.jsx:25 Uncaught TypeError: 无法读取未定义的属性(读取‘photoUrl’)” 这是我的父代码:

import React from 'react';
import { useState } from 'react';
import {getCurrentUser, logout} from '../../services/authService'

import {useNavigate} from "react-router-dom";
import UpdateForm from '../../components/UpdateForm';
import ProfileImage from '../../components/ProfileImage';

import './Profile.css'
import { useEffect } from 'react';


const ProfilePage = () => {
    
    const navigate = useNavigate();
    const [user,setUser] = useState();
    
    useEffect(()=>{
        const getUser = async () => {
            const {data} = await getCurrentUser();
            setUser(data);
        }
        getUser()
    },[])
    
    const handelSignOut =()=>{
        logout();
        setUser('');
        navigate('/sign')
    }
    
    return (
        <div className='prof-con'>
            <div className='prof-flex-wraper'>
               <div className='prof-second-row'>
                    <div className='prof-text'>
                        <ProfileImage user={user}/>
                    </div>
                    <div className='prof-form'>
                        <UpdateForm user={user}/> 
                    </div>
                </div>
            </div>

        </div>
    );
}
export default ProfilePage;

这是个人资料子组件

import React from 'react';
import { useState } from 'react';
import {updatePhoto} from '../services/authService'
import DefaultUserPic from "../images/team-male.jpg";

function ProfileImage({user}) {
    const [previewSrc,setPreviewSrc] = useState(null)
    const [photoSrc,setPhotoSrc] = useState(null)
    
    
    const handelPreview = (e)=>{
        setPreviewSrc(URL.createObjectURL(e.target.files[0]))
        setPhotoSrc(e.target.files[0]);
    }
    
    const handelUpload = ()=>{
       const formData = new FormData();
       console.log(photoSrc)
       formData.append("file", photoSrc);
       updatePhoto(formData);
    }
    
    //console.log(user.photoUrl)
    console.log(user)
    
 
    // if(previewSrc){
    //     var imagestr=previewSrc;
    //     console.log(imagestr)
    //     // imagestr = imagestr.replace("public/", "");
    //     // var profilePic="http://localhost:3001/"+imagestr;
    // }else{
    //      var profilePic='DefaultUserPic';
    // }
    
 
    return (
        <div className='profWraper'>
            <input type="file" name="fileToUpload" id="fileToUpload" onChange={handelPreview}/>
            <img className='profPhoto' src={previewSrc} alt="No-Image" />
            {photoSrc && <button className='uploadBtn' onClick={handelUpload}>Upload</button>}
            
        </div>
    );
}

export default ProfileImage;

如果我记录用户本身,我会在控制台中获取它,但如果我尝试获取任何属性,则会收到未定义的错误。

3个回答

<ProfileImage user={user}/>

更改为

{user && <ProfileImage user={user}/>}

可能会有帮助

vatsal soni
2022-09-02

您正在 ProfileImage 的 useEffect 中异步分配用户。这意味着用户将处于未定义状态,直到异步逻辑解析为止。您必须在访问其属性之前检查用户是否已定义,或者您需要在 useState 中为用户分配某种默认属性。

Brad Melchin
2022-09-02

错误消息表明 user 未定义。考虑到父级执行异步操作来获取 user ,我认为问题在于子级在异步操作解析之前尝试访问 user

解决方案,在子级中添加针对未定义 user 的保护:

if (user === undefined) return
Hasan Aga
2022-09-02