You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React Router中访问页面时如何判断state是否为空并处理解构报错

Fixing the 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 = {} to const { state = {} } = useLocation(): If state is undefined, it defaults to an empty object so destructuring email doesn't fail.
  • Added = null to const { email = null } = state: Ensures email never 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 /chat directly.
  • Cleaned up the API URL: Used template literals instead of concat for 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 13:07:33