繁体   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