gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 13:18:52 25 4
gpt4 key购买 nike

<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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com