简体   繁体   English

React Context API 和 Hooks 有什么区别?

[英]What's the difference between React Context API & Hooks?

As i understand it, they both deal with state.据我了解,他们都处理状态。 Hooks seem to be more internal to a components state, while the context api seems to solve the problem of prop drilling, creating a more global state? Hooks 看起来更像是一个组件状态的内部,而 context api 似乎解决了 prop 钻取的问题,创建了一个更全局的状态? Is this false?这是假的吗? What am I missing?我错过了什么?

Thanks a lot!非常感谢!

As I understand, they have completely different use cases.据我了解,它们有完全不同的用例。 Context allows you pass a value deep into the component tree, where the value could be any kind of prop, say, a color. Context 允许您将值传递到组件树的深处,该值可以是任何类型的道具,例如颜色。 By using context in this way, you avoid having to do props.theme on every component that needs a theme color passed to it.通过以这种方式使用上下文,您可以避免在需要传递给它的主题颜色的每个组件上执行props.theme

Hooks, on the other hand, replace the need for classes;另一方面,Hooks 取代了对类的需求; instead you create a function and useState enables you to pass in variables.相反,您可以创建一个函数,而useState使您能够传入变量。 Ie Hooks allow you to take a React function component and add state to it, and apply lifecycle methods like componentDidMount and componentDidUpdate.即 Hooks 允许您获取 React 函数组件并向其添加状态,并应用诸如 componentDidMount 和 componentDidUpdate 之类的生命周期方法。 This is useful because if you find your function requires state, you don't need to refactor it into a class, you can just add Hooks.这很有用,因为如果您发现函数需要状态,则无需将其重构为类,只需添加 Hooks。 :) Of course this choice is contentious among developers though. :) 当然,这个选择在开发人员中是有争议的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM