reactjs - Context.Consumer 与 useContext() 访问 Context.Provider 传递的值

标签 reactjs react-hooks

<MyContext.Consumer>
    {value => { }}
</MyContext.Consumer>

VS

let value = useContext(MyContext);

这两个片段使用 Context.Consumer 和使用 useContext 钩子(Hook)来访问上下文提供者传递的值有什么区别?我认为 useContext 会订阅上下文提供程序,因为我们将上下文作为参数传递,这样当提供程序值更改时它将触发重新渲染。

最佳答案

这是正确的。他们基本上会做同样的事情。

在我看来,useContext Hook 具有更好、更易读的语法。

来自 React 文档:

https://reactjs.org/docs/hooks-reference.html#usecontext

useContext

const value = useContext(MyContext); Accepts a context object (the value returned from React.createContext) and returns the current context value for that context. The current context value is determined by the value prop of the nearest <MyContext.Provider> above the calling component in the tree.

When the nearest <MyContext.Provider> above the component updates, this Hook will trigger a rerender with the latest context value passed to that MyContext provider.

同样来自 React 文档:

https://reactjs.org/docs/context.html

Context.Consumer

<MyContext.Consumer>
 {value => /* render something based on the context value */}
</MyContext.Consumer>

A React component that subscribes to context changes. This lets you subscribe to a context within a function component.

更新:

来自: http://brianyang.com/react-hooks-a-deeper-dive-featuring-usecontext-and-usereducer/

来自: https://testdriven.io/blog/react-hooks-advanced/

The new useContext hook to consume context does not change the concepts surrounding context, hence the plunge above. This context hook only gives us an extra, much prettier, way to consume context. It's amazingly helpful when applying it to components consuming multiple contexts.

关于reactjs - Context.Consumer 与 useContext() 访问 Context.Provider 传递的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56816374/

相关文章:

javascript - Tabindex 在 Chrome 中不工作(React 应用程序)

html - 按钮内的图标不会触发 React 上的附加功能

reactjs - Recharts CompedChart 从零开始 X 轴刻度

javascript - 无法在 React Native 中使用 useRef() 将 current.focus() 应用于按钮

javascript - 使用 React-Hooks,如何防止从 Array.map 创建的组件在其中一个兄弟组件更改状态时重新呈现?

reactjs - 如何有条件地渲染使用钩子(Hook)的 React 组件

javascript - Sanity.io,有什么方法可以轻松更改字段类型吗?

css - 如何将 Bootstrap <a> 样式应用于导航栏中的 <button>

javascript - 如何使用 React hooks 在 localStorage 中存储初始切换状态

reactjs - 使用 useState 和 useContext React Hooks 持久化 localStorage