React Router中访问页面时如何判断state是否为空并处理解构报错
TypeError When Directly Accessing the /chat Page Hey there! I see exactly what's going on here—when you navigate to /chat from /login, the state gets passed correctly, but hitting the URL directly means there's no state attached to the location at all, hence that frustrating destructuring error. Let's fix this with some simple defensive checks.
The Root Cause
When you use history.push to jump from /login to /chat, you explicitly send the state object along. But if you load /chat directly (like refreshing the page or typing the URL into the address bar), React Router doesn't populate location.state—it's undefined. Trying to destructure email from an undefined value immediately throws that TypeError.
Solution 1: Add Default Values During Destructuring
You can set fallback values when destructuring state and email to avoid errors when they don't exist. Here's your updated Chat component:
import React, { useState, useEffect } from "react"; import axios from 'axios'; import { useLocation } from "react-router-dom"; function Chat() { // Default to empty object if state is undefined const { state = {} } = useLocation(); // Default to null if email isn't present in state const { email = null } = state; const [person, setPerson] = useState([]); useEffect(() => { // Only run the API call if we have a valid email if (email) { axios.get(`localhost:8000/FILLER_${email.toString()}`) .then((res) => { setPerson(res.data); }) .catch(error => { console.log(error); }); } else { // Handle the direct access case—maybe redirect to login? console.log("No user data found! Please log in first."); // Optional: Uncomment below to redirect to login page // useNavigate()('/login'); } }, [email]); // Add email as a dependency so the effect runs if it changes return ( <div> {person.givenname ? ( <h1>Welcome {person.givenname}</h1> ) : ( <h1>Please log in to access this page!</h1> )} </div> ); } export default Chat;
Key Changes Explained:
- Added
= {}toconst { state = {} } = useLocation(): Ifstateis undefined, it defaults to an empty object so destructuringemaildoesn't fail. - Added
= nulltoconst { email = null } = state: Ensuresemailnever stays undefined, even if the state is missing. - Wrapped the API call in an
if (email)check: Prevents unnecessary (and failed) API requests when there's no valid user data. - Conditional render: Shows a friendly message instead of a broken page when accessing
/chatdirectly. - Cleaned up the API URL: Used template literals instead of
concatfor readability.
Solution 2: Explicit Check with Optional Chaining
If you prefer a more concise approach, you can use optional chaining to safely access the email:
function Chat() { const location = useLocation(); const email = location.state?.email || null; // ... rest of your code remains the same }
The ?. operator safely accesses location.state.email only if location.state exists—otherwise it returns undefined, and we fall back to null.
Either approach will eliminate the TypeError and let you handle direct access to /chat gracefully (like redirecting users back to login if needed).
内容的提问来源于stack exchange,提问作者Kazim

