gpt4 book ai didi

javascript - 在 react Prop 中解构嵌套对象出错

转载 作者:行者123 更新时间:2023-12-02 16:14:58 26 4
gpt4 key购买 nike

const {
user: { name }
} = props;

通过上面的代码,我得到了

name of undefined when the user object is undefined

我喜欢破坏,但应该这样使用吗?问题是没有退路让我的 React 应用程序崩溃。我宁愿破坏并使用 ? 作为后备:

const {
user
} = props;

return <div>user?.name</div>

最佳答案

试试这个:

const {
user: { name = '' } = {name: ''}
} = props;

<div>{name}</div>

关于javascript - 在 react Prop 中解构嵌套对象出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66964937/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com