【问题标题】:How to fix: 'Object is possible undefined' in react with typescript and mobx如何修复:“对象可能未定义”与 typescript 和 mobx 反应
【发布时间】:2019-05-23 17:45:20
【问题描述】:

我有一个 mobx 商店 (AnimalStore),其中有一个可观察的动物列表。而且,我有两个组件(ParentComponent 和 ChildComponent)。

在 ParentComponent 上,我显示了动物总数,这是我从 mobx 注入商店 (animalStore.animals) 的可观察列表中获得的。在 ChildComponent 上,我显示了所有的动物,也是来自 mobx 注入商店 (animalStore.animals) 的可观察列表。

在 ParentComponent 上,我根据需要设置 store 的 props 接口。在 ChildComponent 上,我将商店的道具设置为可选。

但是,当我尝试访问 this.props.animalStore 时,我在 ChildComponent 上遇到打字错误:

对象可能未定义。

但是,如果我根据需要更改 ChildComponent 的可选存储道具,错误 Object is possible undefined. 就会消失,但是,在 ParentComponent 上我会收到错误:

“{}”类型中缺少 animalStore 的属性,但在“只读”类型中是必需的。

// ParentComponent.tsx

interface IProps {
    animalStore: AnimalStore
}

@inject('animalStore')
@observer
export default class ParentComponent extends React.Component<IProps> {
    render() {
        return (
            <View style={styles.container}>
                <Text>Total animals: {this.props.animalStore.animals.length}</Text>
                <SecondComponent/>
            </View>
        )
    }
}


// ChildComponent.tsx 

interface IProps {
    animalStore?: AnimalStore
}

@inject('animalStore')
@observer
export default class ChildComponent extends React.Component<IProps> {
    render() {
        return (
            <ScrollView style={styles.container}>
                {
                    this.props.animalStore.animals.map((el: string) => {
                        return <Text key={el}>{el}</Text>
                    })
                }
            </ScrollView>
        )
    }
}

我想我可以通过!Non-null assertion operator 解决这个问题,但是有没有其他方法可以解决这个打字稿问题?

【问题讨论】:

    标签: reactjs typescript


    【解决方案1】:

    根本原因

    您的 ChildComponent 将 prop 定义为可为空的。注意问号:

    interface IProps {
        animalStore?: AnimalStore
                   ^
                   |
                   makes it nullable (AnimalStore | undefined)
    }
    

    解决方案

    您有几个选项,每个选项都可以成为解决问题的有效方法,具体取决于您应用的更广泛上下文。

    选项 1 -- 不要通过删除 ? 来声明它可以为空

    接口 IProps { 动物商店:动物商店; }

    选项 2 -- 使用 non-null assertion ! operator 强制将其视为非虚假值:

    <ScrollView style={styles.container}>
      {
        this.props.animalStore!.animals.map((el: string) => {
                              ^
          return <Text key={el}>{el}</Text>
        })
      }
    </ScrollView>
    

    选项 3 -- 编写防御性代码,期望 store 可能为空值:

    const {animalStore} = this.props;
    
    <ScrollView style={styles.container}>
      {
        animalStore ?
          animalStore.animals.map((el: string) => {
            return <Text key={el}>{el}</Text>
          }) :
          <Text>Loading Animal Store...</Text>
      }
    </ScrollView>
    

    【讨论】:

      猜你喜欢
      • 2019-08-20
      • 2019-12-09
      • 1970-01-01
      • 2020-08-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多