您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

Redux 安装

R 安装

R作为NPM上的软件包提供,可与模块捆绑器或Node应用程序一起使用:

# NPM
npm install r

# Yarn
yarn add r

它也可以作为预编译的UMD软件包来使用,该软件包定义了window.R。

UMD包可以直接用作。

npm install --save r

以上基于使用  来做的情况下。

否则你可以直接在 ,下载下来,或者把让你的指向它。

一般情况下人们认为 R 就是一些  模块的集合。这些模块就是你在使用 、、或者 Node 环境时引入的。如果你想追求时髦并使用 ,也是的。

你也可以不使用模块打包工具。r 的 npm 包里 包含了预编译好的生产环境和开发环境下的  。可以直接使用,而且大部分流行的 JavaScript 包加载器和环境。比如,你可以直接在上的 <script>  中引入 UMD ,也可以。UMD 可以让你使用 window.R 来访问 R。

R 源由 ES2015 编写,但是会预编译到 CommonJS 和 UMD 规范的 ES5,所以它可以 。你不必非得使用 Babel 或模块打包器来使用 R。

多数情况下,你还需要使用 和。

npm install --save react-r
npm install --save-dev 

需要提醒的是,和 R 不同,很多 R 生态下的包并不提供 UMD ,所以为了提升开发体验,我们建议使用像  和  这样的 CommonJS 模块打包器。

R 终极版工具包

R本身很小,并且不受限制。我们还有名为的单独的程序,其中包含一些自以为是的认值,可帮助您更有效地使用R。这是编写R逻辑的官方推荐。

RTK包含有助于简化许多常见用例的实用程序,, ,甚至立即。

无论您是设置您的第项目的全新R,还是想简化现有应用程序的资深,都可以帮助您改善R。

创建 React R 应用

推荐的方式开始与新的应用程序反应,终极版是通过用于,这需要的优势和应对与反应的组分终极版的集成。

npx create-react-app my-app --template r

R 基本示例

应用程序的整个状态存储在单个商店内的对象树中。更改状态树的唯一是发出action,描述发生了什么的对象。要指定动作如何转换状态树,您可以编写pure reducers。

import { createStore } from 'r'
/**
 * This is a reducer, a pure function with (state, action) => state signature.
 * It describes how an action transforms the state into the next state.
 *
 * The shape of the state is up to you: it can be a primitive, an array, an object,
 * or even an Immutable.js data structure. The only important part is that you should
 * not mutate the state object, but return a new object if the state changes.
 *
 * In this example, we use a `switch` statement and strings, but you can use a helper that
 * follows a different convention (such as function maps) if it makes sense for your
 * project.
 */
function counter(state = 0, action) {
  switch (action.type) {
    case 'INCREMENT':
      return state + 1
    case 'DECREMENT':
      return state - 1
    default:
      return state
  }
}

// Create a R store holding the state of your app.
// Its API is { subscribe, dispatch, getState }.
let store = createStore(counter)

// You can use subscribe() to update the UI in response to state changes.
// Normally you'd use a view binding library (e.g. React R) rather than subscribe() directly.
// However it can also be handy to persist the current state in the localStorage.

store.subscribe(() => console.log(store.getState()))

// The only way to mutate the internal state is to dispatch an action.
// The actions can be serialized, logged or stored and later replayed.
store.dispatch({ type: 'INCREMENT' })
// 1
store.dispatch({ type: 'INCREMENT' })
// 2
store.dispatch({ type: 'DECREMENT' })
// 1

您可以直接使用状态对象(称为action)指定要发生的变化,而不是直接改变状态。然后,编写称为reducer的特殊,以决定每个动作如何转换整个应用程序的状态。

在典型的R应用程序中,只有具有单个根减少的商店。随着您的应用程序的增长,您将根减速器拆分为较小的减速器,分别在状态树的不同部分上运行。这就像React应用程序中只有根组件一样,但是它由许多小组件组成。

对于反应用程序而言,这种体系结构似乎有些过头了,但是这种模式的优点在于可以很好地扩展到大型和复杂的应用程序。它还可以启用非常强大的开发人员工具,因为可以跟踪每个突变的发生原因。您可以记录会话并仅通过重播每个操作来重现它们。


联系我
置顶