Redux VS 上下文 API [英] Redux VS Context API

查看:52
本文介绍了Redux VS 上下文 API的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我非常熟悉 Context API,我完成了 Redux 的速成课程,它们在我看来(原则上)很相似.问题是,我应该关注哪一个?Context API 和 Redux 之间的主要优缺点是什么?哪个在 React 状态管理中最好.

I am very familiar with Context API, I completed a crash course with Redux and they both appear alike (in principle) to me. The question is, which one should I focus on? What are the major Pros and Cons between Context API and Redux?. Which is best in React State management.

推荐答案

Context 和 Redux 是非常不同的工具,可以解决不同的问题,有一些重叠.

Context and Redux are very different tools that solve different problems, with some overlap.

上下文不是状态管理";工具.这是一种依赖注入机制,其唯一目的是使嵌套的 React 组件树可以访问单个值.由您决定该价值是什么以及它是如何创建的.通常,这是使用来自 React 组件状态的数据完成的,即 useState 和 useReducer.所以,你实际上是在做所有的状态管理".你自己 - 上下文只是给你一种将它传递给树的方法.

Context is not a "state management" tool. It's a Dependency Injection mechanism, whose only purpose is to make a single value accessible to a nested tree of React components. It's up to you to decide what that value is, and how it's created. Typically, that's done using data from React component state, ie, useState and useReducer. So, you're actually doing all the "state management" yourself - Context just gives you a way to pass it down the tree.

Redux 是一个库和模式,用于将状态更新逻辑与应用程序的其余部分分开,并可以轻松跟踪状态何时/何地/为什么/如何更改.它还使您的整个应用能够访问任何组件中的任何状态.

Redux is a library and a pattern for separating your state update logic from the rest of your app, and making it easy to trace when/where/why/how your state has changed. It also gives your whole app the ability to access any piece of state in any component.

所以,是的,您可以同时使用它们来向下传递数据,但它们不是一回事.

So, yes, you can use both of them to pass data down, but they're not the same thing.

更多详情,请看我的帖子:

For more details, see my posts:

这篇关于Redux VS 上下文 API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆