reactjs / reactjs/react.dev

context.md example, when not to use contexts

未關閉
#3,288 0 則留言 0 個 reaction 已指派 0 人 在 GitHub 檢視

還沒有人認領這個 Issue。

主要語言
JavaScript
星號
11.8k
分支
7.9k
平均合併
1 天 11 小時
30 天內合併 PR
11

描述

I'm sorry if this comes across the wrong way. I understand the concept of contexts. What I don't quite understand is this example when to not use them.

It shows this example

<Page user={user} avatarSize={avatarSize} />
// ... which renders ...
<PageLayout user={user} avatarSize={avatarSize} />
// ... which renders ...
<NavigationBar user={user} avatarSize={avatarSize} />
// ... which renders ...
<Link href={user.permalink}>
  <Avatar user={user} size={avatarSize} />
</Link>

Being replaced by this

function Page(props) {
  const user = props.user;
  const userLink = (
    <Link href={user.permalink}>
      <Avatar user={user} size={props.avatarSize} />
    </Link>
  );
  return <PageLayout userLink={userLink} />;
}

// Now, we have:
<Page user={user} avatarSize={avatarSize} />
// ... which renders ...
<PageLayout userLink={...} />
// ... which renders ...
<NavigationBar userLink={...} />
// ... which renders ...
{props.userLink}

and claims

This inversion of control can make your code cleaner in many cases by reducing the amount of props you need to pass through your application and giving more control to the root components.

My gut reaction was the opposite. The Page component now needs to know details of the NavigationBar (it needs to know what elements/components NagivationBar needs. The Page component seems like it should have zero knowledge of what's in the NavigationBar. It should be passing down some opaque hunk of data and letting NavigationBar deal with it. That it does need to know the details is a strong coupling, not a loose coupling.

Is that a bad example that's trying to illustrated some bigger point but the example is just poorly chosen or am I maybe mis-understanding something?

貢獻指南

開啟貢獻指南

從這裡開始

  1. 先讀完整個 Issue,再讀專案的貢獻指南。
  2. 在 Issue 下留言說明你要接手 —— 這能避免兩個人做同樣的事。
  3. Fork 儲存庫,在一個分支上完成修改。
  4. 送出 Pull Request,並在描述裡引用這個 Issue 編號。

研究方向

先閱讀 context.md 中包含「何時不使用 contexts」範例及其周圍說明的部分。比較範例所述的 inversion-of-control 優點與此處提出的耦合疑慮,然後釐清或修訂範例,讓其預期的指引與取捨清楚明確。

由索引模型根據 Issue 內容生成。

評估

技術堆疊
react
領域
documentation
Issue 類型
文件
難度
3/5
預估耗時
1-2 天
活躍度
停滯
描述清晰度
需要釐清
新手友好度
42/100

把新 issue 寄到你的電子郵件信箱

精選適合新手參與的 GitHub issue 摘要。