ค้นหาเว็บไซต์

reactjs - แสดงข้อผิดพลาดว่า Object อาจเป็น 'undefined' แม้หลังจากตรวจสอบแล้วว่า object และ property นั้นมีอยู่


ฉันได้รับข้อผิดพลาด Object is possibly 'undefined'. ทุกครั้งที่ตรวจสอบและเข้าถึง property หลังจาก story && ในโค้ดด้านล่าง ซึ่งมันไม่เข้าใจสำหรับฉันเลย เพราะการตรวจสอบครั้งแรกกำลังตรวจสอบว่า story มีอยู่หรือไม่ หากมันไม่มีอยู่ การตรวจสอบแบบ ternary จะไม่ดำเนินการต่อและคืนค่า null ใช่ไหม? ฉันเพิ่งเริ่มใช้ TypeScript (และก็เริ่มใช้ React) ฉันยินดีที่จะรับข้อเสนอแนะใด ๆ ขอบคุณ!

import React, { useState, useEffect } from "react";
import { getStory } from "../services/hnAPI";

interface Props {
  storyId: number;
}

export const Story: React.FC<Props> = (props) => {
  const [story, setStory] = useState();
  useEffect(() => {
    getStory(props.storyId).then((data) => data && data.url && setStory(data));
  }, [props.storyId]);
  return story && story.url ? (
    <a href={story.url}>{story.title}</a>
  ) : null;
};

คำตอบ #1

คุณควรส่งอาร์กิวเมนต์ประเภทให้กับ useState() เพื่อไม่ให้มันสันนิษฐานค่าของ state เป็น undefined

นี่คือตัวอย่าง

import React, { useState, useEffect } from 'react';
import { getStory } from '../services/hnAPI';

interface Props {
  storyId: number;
}

interface Story {
  id: number;
  title: string;
  url: string;
  // properties for the Story
}

export const Story: React.FC<Props> = (props) => {
  const [story, setStory] = useState<Story | null>(null);
  useEffect(() => {
    getStory(props.storyId).then((data: Story) => data && setStory(data));
  }, [props.storyId]);
  return story && story.url ? <a href={story.url}>{story.title}</a> : null;
};

ป.ล. กรุณาอย่าปล่อยให้คำสัญญาไม่ได้รับการจับ ถ้าคุณกำลังทำการเรียก API และใช้ฟังก์ชัน getStory ของคุณ ควรพิจารณาเพิ่มบล็อก catch และจัดการข้อผิดพลาดอย่างเหมาะสม ตัวอย่างในสถานการณ์เดียวกัน

export const Story: React.FC<Props> = (props) => {
  const [story, setStory] = useState<Story | null>(null);
  useEffect(() => {
    getStory(props.storyId).then((data: Story) => data && setStory(data))
      .catch(error => {
          // handle the error
          // you can use another state variable to store the error
      });
  }, [props.storyId]);
  return story && story.url ? <a href={story.url}>{story.title}</a> : null;
};

บทความที่เกี่ยวข้อง