簡體   English   中英

在React / TypeScript應用程序中初始化可為空狀態的正確方法是什么?

[英]What is the proper way of initializing nullable state in React/TypeScript apps?

使用TypeScript接口/類型在React中初始化初始空(null)狀態的正確方法是什么? 例如,我有一個接口:

interface IObject {
  name: string,
  age: number,
  info: IAnotherObject
}

和一個簡單的組件,其中我想將initial information state as null定義initial information state as null (不創建一個實現我的接口並為所有屬性塑造默認值的類),但使用IObject接口

interface IState {
  information: null|IObject;
}

class App extends React.Component<{}, IState> {
 state = {
  information: null
 };

 componentDidMount() {
  // fetch some data and update `information` state
 }

 render() {
   <div>
    {this.state.information &&
    <div>
      <div>{this.state.information.name}</div>
      <div>//other object data</div>
    </div>
   </div>
 }

我們是否有另一種使用union類型初始化可空狀態的方法:

// worked way, but with union null type
interface IState {
  information: null|IObject;
}
// some another way(no union), but with initial `null` or `undefined`
interface IState {
  information: IObject;
}

state = {
 information: null
}

(對於我要為每個我想要初始為空值的對象使用null注釋,這似乎不是很“聰明”)類型對象?

如果您想擁有初始的空狀態,則應該這樣做,

將信息標記為空,

interface IState {
  information?: IObject;
}

現在您可以將其初始化為空。

state = {}

對於缺少的屬性,應依靠undefined而不是null 從打字稿樣式指南中,( 鏈接

使用未定義。 不要使用null。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM