我的一个 friend 的 React 应用程序中有这段代码,我需要明确地理解这段代码的作用:
const Component = ()=> (
<QueryFetcher>
{({ data }) => {
const { user: { profile = {} } = {} } = data
return (
<div>
{profile.username && profile.username}
</div>
)
}}
</QueryFetcher>
)
这条线是做什么用的?
const { user: { profile = {} } = {} } = data
在这个功能组件中使用 { user: { profile = {} } = {} }
为 {}
赋值是否正确?或者在 React 中有状态组件的 render()
Hook 中?
最佳答案
const { user: { profile = {} } = {} } = data
基本上意味着您正在检索用户个人资料。
const
表示您正在创建一个新变量
{ user: { profile } } }
表示您正在检索用户内部的个人资料
= {}
表示如果对象未定义,则使用空对象,这样它就不会失败,因为如果用户未定义,执行 user.profile 会抛出错误。
= data
表示您从数据变量中检索此信息
因此,这一行的意思是,从变量数据中获取用户,如果用户未定义,则使用空对象。然后,获取配置文件,如果配置文件未定义,则使用空对象。然后用结果创建一个名为 profile 的变量。这就像这样做:
const user = data.user === undefined ? {} : data.user;
const profile = user.profile === undefined ? {} : user.profile;
关于Javascript,在 React 应用程序中分配给函数组件中的 {},代码审查,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55928240/