缺少null或未定义

缺少null或未定义

本文介绍了流类型属性"msg"缺少null或未定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现很难使用Flow.我知道Array.find可以返回或不确定.

I am finding hard to use Flow. I understand that Array.find can return or be undefined.

因此,通过阅读以下内容: github:Array.find on Array< {...}> ;加薪

So by reading this: github: Array.find on Array<{...}> raises

我这样做了,并在类型中添加了void.但是现在我得到了错误:

I did that and added void to the type to. However now I get the error:

检查代码以查看错误的具体位置.

Check code to see where the error is specifically.

我理解为什么它会给我错误,未定义中没有msg.我不知道该如何解决这个问题.

I understand why it is giving me the error, there is no msg in undefined. what I don't know is how to solve this issue.

这是代码:

type StageMsg = {
  stage: number,
  msg?: string
};

let stageMsg: void | StageMsg = this.stages.find(
  (obj: StageMsg) => obj.stage === this.state.stage
);

msg = (
  <Msg text={this.state.msg !== "" ? this.state.msg : stageMsg.msg} /> //<---- [Error here].
);

推荐答案

您只需要检查stageMsg存在,然后再访问该属性即可.
因此,您可以将您的任务包装到if (stageMsg) { ... }中的msg,或者使用内联表达式,例如stageMsg && stageMsg.msg.
另外请注意,您可以使用也许语法,而不要使用与void的联合,例如let stageMsg: ?StageMsg

You just need to check that stageMsg exists before accessing a property on it.
So you could wrap your assigment to msg in if (stageMsg) { ... }, or use an inline expression like stageMsg && stageMsg.msg.
Also note that you could use maybe syntax instead of a union with void e.g. let stageMsg: ?StageMsg

这篇关于流类型属性"msg"缺少null或未定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-31 22:22