如何在状态由未定义的道具初始化时保护防止应用程序崩溃?

huangapple go评论87阅读模式
英文:

How to protect breaking app when state is initialized by props of undefined?

问题

如何在props.native_languages[0]不存在时保护状态不被破坏?

这是我尝试保护的方式,但是当native_languages[0]不存在时应用程序会崩溃:

 this.state = {
      language: props.currentDocument.native_languages[0] || 'en',
 };
英文:

How to protect state from breaking when props native_langugaes[0] does not exist?

This is how I tried to protect, but app break when native_langugages[0] does not exist:

 this.state = {
      language: props.currentDocument.native_languages[0] || 'en',
 };

答案1

得分: 2

也许 native_languages 也不存在。尝试使用 lodash.get

https://www.npmjs.com/package/lodash.get

this.state = {
   language: get(props, 'currentDocument.native_languages[0]', 'en'),
};
英文:

Maybe native_languages does not exist either. Try to use lodash.get:

https://www.npmjs.com/package/lodash.get

this.state = {
   language: get(props, 'currentDocument.native_languages[0]', 'en'),
};

答案2

得分: 1

你可以尝试一个三元运算符:

this.state = {
  language: props.currentDocument.native_languages 
    ? props.currentDocument.native_languages[0] || 'en' 
    : 'en'
};
英文:

You can try a ternary:

this.state = {
  language: props.currentDocument.native_languages 
    ? props.currentDocument.native_languages[0] || 'en' 
    : 'en'
};

答案3

得分: 1

虽然所有建议都很不错,但你应该考虑查看defaultProps,因为在我看来,这似乎是一种更清晰的方法来做这件事。

英文:

While all suggestions seems good, you should consider taking a look at defaultProps as it seems to me a cleaner way to do it.

huangapple
  • 本文由 发表于 2020年1月6日 20:04:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/59611790.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定