即使检查对象和属性是否存在,对象也可能是“未定义”错误

时间:2020-05-25 02:17:10

标签: reactjs typescript react-typescript

在以下代码的Object is possibly 'undefined'.之后,每次属性检查和访问都遇到story &&错误。这对我来说没有意义,因为第一个检查是检查story是否存在。如果不存在,那么三进制是否会短路并返回null?我是打字稿新手(也刚开始做出反应)。我很高兴听到任何建议!谢谢!

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 个答案:

答案 0 :(得分:2)

您应该将类​​型参数传递给useState(),以便它不会将状态值推断为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;
};

P.S。请永远不要兑现诺言。如果您要进行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;
};