Context.Consumer vs useContext() 访问由 Context.Provider 传递的值

Context.Consumer vs useContext() to access values passed by Context.Provider

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

VS

let value = useContext(MyContext);

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

没错。他们基本上会做同样的事情。

在我看来,useContext 挂钩的语法更好、更易读。

来自 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 above the calling component in the tree.

When the nearest 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/

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.