【问题标题】:What is the proper way of initializing nullable state in React/TypeScript apps?在 React/TypeScript 应用程序中初始化可为空状态的正确方法是什么?
【发布时间】:2019-03-23 04:27:34
【问题描述】:

使用 TypeScript 接口/类型在 React 中初始化初始空(null)状态的正确方法是什么? 比如我有一个接口:

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

和一个简单的组件,我想在其中定义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注释每个我想要初始空值的对象似乎不是很“聪明”)在状态中键入对象?

【问题讨论】:

    标签: javascript reactjs typescript


    【解决方案1】:

    如果你想有初始的空状态,你应该这样做,

    将信息标记为空,

    interface IState {
      information?: IObject;
    }
    

    现在您可以将其初始化为空。

    state = {}
    

    对于缺少的属性,您应该依赖 undefined 而不是 null。来自打字稿样式指南,(link)

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-04-20
      • 1970-01-01
      • 1970-01-01
      • 2019-06-15
      • 2018-12-31
      • 2018-07-23
      • 2019-09-30
      • 1970-01-01
      相关资源
      最近更新 更多