我的朋友在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()
钩中?
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;
这条线是干什么用的?
const { user: { profile = {} } = {} } = data
它基本上只是用默认值链接的 ES6 对象解构。这行用文字做什么:
- 从"数据"中读取"用户",如果未定义"用户",则分配 {} 作为默认值
- 从"用户"中读取"配置文件",如果未定义"配置文件",则分配 {} 作为默认值
正确吗
它主要是一种用于删除重复内容的简写语法。因此,而不是分别访问多个对象道具,例如
this.props.prop1, this.props.prop2, ...
您可以使用
const { prop1, prop2 } = this.props;
它还可以帮助其他读者以后快速理解如果所有必要的 props 在开始时被解构,则方法中使用了哪些变量。