首页 > 解决方案 > 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 中的有状态组件的钩子中?

标签: javascriptreactjsperformancedestructuring

解决方案


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;

推荐阅读