英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论