use*_*386 4 typescript reactjs 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;
};
Run Code Online (Sandbox Code Playgroud)
您应该传递一个类型参数,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;
};
Run Code Online (Sandbox Code Playgroud)
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;
};
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5959 次 |
| 最近记录: |