React项目中登录验证成功后提示框显示用户名undefined的问题求助
Hey there! The issue you're seeing (Welcome undefined) comes down to how you're validating users and accessing their name. Let's break it down and fix it:
What's Wrong?
You're using Array.some() to check for a valid user, which only returns a boolean (true if a matching user exists, false otherwise). It doesn't actually give you the specific user object that matched the credentials.
When you try to use Users.name, you're trying to access a name property directly on the Users array itself—arrays don't have a name property, so you end up with undefined.
The Fix
Replace Array.some() with Array.find(). Unlike some(), find() returns the first matching user object (or undefined if no match is found). This lets you access the user's name property correctly.
Here's your updated login function:
const login = (details) => { // Find the exact user that matches the email and password const matchedUser = Users.find((user) => { return user.email === details.email && user.password === details.password; }); if (matchedUser) { // Now we can safely access the matched user's name toast.success(`Welcome ${matchedUser.name}`); navigate("/"); } else { toast.error("臘♂️ Invalid email or password! Please check your entries."); } };
Bonus Tip
If you plan to use the logged-in user's information elsewhere in your app, consider storing matchedUser in a React state (using useState). This way, you can access the user's details across components instead of just showing it in a toast.
内容的提问来源于stack exchange,提问作者Tony

