简体   繁体   English

useState:解构嵌套的 object 和 typescript

[英]useState: destructure nested object with typescript

I'm trying to destructure an object in useState so I can directly use the properties.我正在尝试在 useState 中useState以便我可以直接使用这些属性。 But I am not sure about the correct syntax to use with typescript.但我不确定与 typescript 一起使用的正确语法。

Here is the interface for "topic":这是“主题”的界面:

export interface ITopic{
    title: string
    text?: string
    posts?: string[]
}

Without destructuring it would look like:没有解构它看起来像:

const [topic, setTopic] = useState<ITopic>()

To destructure, I have tried a few things,for instance this doesn't work:为了解构,我尝试了一些东西,例如这不起作用:

const [{title, text, posts}: ITopic, setTopic] = useState<ITopic>();

It says (if I hover over title and setTopic):它说(如果我 hover 超过标题和 setTopic):

  • Property 'title' does not exist on type 'ITopic | 'ITopic | 类型上不存在属性'title' undefined'不明确的'
  • Tuple type '[ITopic |元组类型'[ITopic | undefined, Dispatch<SetStateAction<ITopic |未定义,调度<SetStateAction<ITopic | undefined>>]' of length '2' has no element at index '2'.长度为 '2' 的 undefined>>]' 在索引 '2' 处没有元素。

Use an initial value.使用初始值。 Because you don't have an initial value, it detects on the first render that this cannot be destructured.因为您没有初始值,所以它会在第一次渲染时检测到它不能被解构。

export interface ITopic{
    title: string
    text?: string
    posts?: string[]
}

const [{title, text, posts}, setTopic] = useState<ITopic>({
    posts: [],
    text: '',
    title: ''
});

The second approach is to add a check in the forms of loading data:第二种方法是在加载数据的forms中添加一个检查:

const [topic, setTopic] = useState<ITopic | undefined>() 
// explicitly define the type as "undefined", which is unnecessary, but a good indicator

if(!topic) return <div>loading</div>;

const {title, text, posts} = topic; // then you can safely destructure the object

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM