I try to "get" "user information" from the server.
API GET url is:/users/${memberId} userID is a numeric type memberId (Example 4)
The following are my questions..
When I click on "userIcon" on " " I should link the page and load the correct user information
When I try to check the localhost's page directly, it doesn't show up. But when I remove " userId={userData.memberId} " the page shows and rewrites "userId={userData.memberId}" and save, the page is normal.
//Header.tsx
useEffect(() => {
const userGetData = async () => {
return call(`/users`, 'GET', null)
.then((res) => {
const data = res[0]
setUserData(data);
});
};
userGetData();
}, [])
...
return(
...
<div>
<LoginHeader changeNav={isUser.isLogin} userID={userData.memberId} />
</div>
)
The link in "userId={userData.memberId}" is used for the path UserPage. This is console.log(userData)
Enter image description here
//LoginHeader.tsx
// UserIcon
<Link to={`/users/${userID}`}
state={{userID: userID}}
className="relative p-2 text-gray-500 bg-transparent"
>
<img/>
</Link>
The problem is when I click on the UserIcon it doesn't work and I get an error. The error tells me<<无法读取未定义的属性(读取'memberId')>>
So..why doesn't my code work? : Click the user icon -> Go to UserPage using uerl /users/${memberId}. Why doesn't useEffect 'GET' work until I remove the memberId prop in LoginHeader? ? ?
Because
userDataisundefined. You don't show where/how you initialize it, but something like this? :This will initialize it to
undefined. So when the component first renders, you cannot read the property fromuserDatabecause it isundefined. It may have a value at a later time but by then the code has already thrown the error.One option is to initialize it as an empty object:
const [userData, setUserData] = useState({});In this case,
userData.memberIdwill not throw an error, but will pass anundefinedvalue to the component.Another option is to not render the component until
userDatahas a value:<div> { userData ? <LoginHeader changeNav={isUser.isLogin} userID={userData.memberId} /> : null } </div>Which option you prefer is entirely up to you. But the main thing is that you cannot read properties from
undefined.