|
Post by account_disabled on Jan 27, 2024 20:19:14 GMT -8
React使用组件和单向数据流的方式使其成为描述用户界面结构的理想选择。然而,它处理状态的工具故意保持简单——以帮助提醒我们,React 只是传统模型-视图-控制器架构中的视图。 Pause Next Unmute Current Time 0:10 / Duration 2:00 Fullscreen 没有什么可以阻止我们仅使用 React 构建大型应用程序,但我们很快就会发现,为了保持代码简单,我们需要在其他地方管理我们的状态。 虽然没有处理应用程序状态的官方解决方案,但有一些库与 React 的范例特别契合。在这篇文章中,我们将 React 与两个这样的库配对,并使用它们构建一个简单的应用程序。 终极版 Redux是一个小型库,通过结合Flux和Elm的思想,充当我们应用程序状态的容器。我们可以使用 Redux 来管理任何类型的应用程序状态,只要我们遵守以下准则: 我们的状态保存在一个存储中 变化来自行动而不是突变 Redux 存储的核心是一个函数,它获取当前应用程序状态和操作,并将它们组合起来创建新的应用程序状态。我们将此函数称为“ reducer”。 我们的 React 组件将负责将操作发送到我们的存储,反过来我们的存储将告诉组件何时需要重新渲染。 不可变JS 由于 Redux 不允许我们改变应用程序状态,因此通过使用不可变数据结构对应用程序状态进行建模 WhatsApp 号码数据 来强制执行此操作会很有帮助。 ImmutableJS为我们提供了许多具有可变接口的不可变数据结构,并且它们以有效的方式实现,受到 Clojure 和 Scala 中实现的启发。 演示 我们将使用 React 与 Redux 和 ImmutableJS 来构建一个简单的待办事项列表,该列表允许我们添加待办事项并在完整和不完整之间切换。 该代码可在GitHub 上的存储库中找到。 设置 我们将首先创建一个项目文件夹并package.json使用npm init. 然后我们将安装我们需要的依赖项。 npm install --save react react-dom redux react-redux immutable npm install --save-dev webpack babel-core babel-loader babel-preset-es2015 babel-preset-react 我们将使用JSX和ES2015 ,因此我们将使用Babel编译代码,并且我们将将此作为使用Webpack 的模块捆绑过程的一部分。 如何将 Redux 与我的 React 组件连接? 您可以使用connect该react-redux库提供的功能将您的 React 组件与 Redux 存储连接起来。此函数允许组件访问状态并调度操作。 Redux 中某个操作的目的是什么? 操作是简单的 JavaScript 对象,用于描述应用程序中的事件或更改。它们被分派到 Redux 存储以触发状态更新。操作通常具有类型属性和可选的有效负载。 什么是Reducer,它们在 Redux 中如何工作? ducers 是指定应用程序的状态如何响应操作而变化的函数。它们将当前状态和操作作为输入并返回新状态。 Rebx、Recoil 和 Context API(带有 useReducer),可用于 React 中的状态管理。选择取决于您的具体项目要求和偏好。 分享此文章 丹·普林斯 丹·普林斯 Digital Nomad 是英国初创公司 Astral Dynamics 的联合创始人。 gitCS 不可变.js javascript 尼尔森 反应 反应中心 React 项目 还原 SitePoint 高级版
|
|