reactjs / reactjs/react.dev

React Hooks docs: add an useContext example where state is updated within a functional component

未关闭
#1,604 6 条评论 1 个 reaction 已指派 0 人 在 GitHub 查看

还没有人认领这个 Issue。

question
主要语言
JavaScript
星标
11.8k
派生
7.9k
平均合并
1 天 11 小时
30 天内合并 PR
11

描述

The React Hooks docs has in the useContext section an example where state is updated within a class component. How is this done within a functional component?

I did this example https://codesandbox.io/s/3vxr57vm7q but I am wondering if it is possible with less DRY, especially in index.js, lines 10-18:

  const [count, setCount] = useState(0)

  return (
    <Context.Provider
      value={{
        count: count,
        setCount: setCount
      }}
    >

With just one state property and one setState function it's ok but imagine you have five of those pairs, then you must repeat every one three times (eg.: count in useState, as key and as property in <Context.Provider />).

Hence, an example would be great and if I did it the right way.

贡献指南

打开贡献指南

从这里开始

  1. 先读完整个 Issue,再读项目的贡献指南。
  2. 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
  3. Fork 仓库,在一个分支上完成修改。
  4. 提交 Pull Request,并在描述里引用这个 Issue 编号。

调研方向

从 React Hooks 文档的 useContext 部分开始,并将其与链接的 CodeSandbox 进行比较,尤其是 index.js 的第 10-18 行。完成的标准是:该部分包含一个函数组件示例,展示如何更新 context state,并说明重复的 state 和 setter 属性是否可以简化。

由索引模型根据 Issue 内容生成。

评估

技术栈
javascript, react
领域
documentation
Issue 类型
文档
难度
2/5
预计耗时
1-3 小时
活跃度
停滞
描述清晰度
基本清楚
新手友好度
45/100

把新 issue 发到你的邮箱

精选适合新手参与的 GitHub issue 摘要。