2

在下面的代码中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;
};
4

1 回答 1

5

您应该将类​​型参数传递给,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;
};

PS请永远不要让承诺落空。如果您正在进行 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;
};

于 2020-05-25T02:53:33.473 回答