【发布时间】: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