javascript - Javascript,在 React 应用程序中分配给函数组件中的 {},代码审查
问题描述
我的一个朋友的 React 应用程序中有这段代码,我需要了解这段代码的作用:
const Component = ()=> (
<QueryFetcher>
{({ data }) => {
const { user: { profile = {} } = {} } = data
return (
<div>
{profile.username && profile.username}
</div>
)
}}
</QueryFetcher>
)
这条线是干什么用的?
const { user: { profile = {} } = {} } = data
在这个功能组件中分配一些东西{}
使用是否正确?{ user: { profile = {} } = {} }
还是render()
在 React 中的有状态组件的钩子中?
解决方案
const { user: { profile = {} } = {} } = data
基本上意味着您正在检索用户个人资料。
const
意味着您正在创建一个新变量
{ user: { profile } } }
表示您正在用户内部检索个人资料
= {}
表示如果对象未定义,请使用空对象,这样它就不会失败,因为如果 user 未定义,执行 user.profile 将引发错误。
= data
表示您从数据变量中检索此信息
所以,这一行的意思是,从变量数据中,去取用户,如果用户未定义,则使用一个空对象。然后,获取配置文件,如果配置文件未定义,则使用空对象。然后使用结果创建一个名为 profile 的变量。这就像这样做:
const user = data.user === undefined ? {} : data.user;
const profile = user.profile === undefined ? {} : user.profile;
推荐阅读
- .net-core - Travis:E:无法找到包 dotnet-sdk-2.0.0
- android - 如何在 BottomSheetDialogFragment 中使用 getViewLifecycleOwner()
- python - 使用 route53domains 进行 boto3 分页
- reactjs - 如何显示区块链合约调用的时间?
- c - 二维数组和指针
- google-bigquery - 如何从 BigQuery API 获取列名?
- python - 在每行开头添加 2 个空格的文本标记
- anomaly-detection - 何时在 Azure Anomaly Detector 中使用“/entire”与“/last” API?
- python - 为什么我的快速排序程序不能正确排序项目?
- java - 如何使反向排序与泛型类类型一起使用