Day 140/200 Redux中的基本定义说明(含Reducer部分)


写在前面的话

学东西,要先看官网~

(一)Redux

1、定义

Redux 是 JavaScript 应用的状态容器,提供可预测的状态管理。

Redux 是一个使用叫做“action”的事件来管理和更新应用状态的模式和工具库 它以集中式Store(centralized store)的方式对整个应用中使用的状态进行集中管理,其规则确保状态只能以可预测的方式更新。

Redux 除了和 React 一起用外,还支持其它界面库。它体小精悍(只有2kB,包括依赖),却有很强大的插件扩展生态。

2、安装方式

# NPM

npm install redux

# Yarn

yarn add redux

复制代码

3、基本逻辑

应用的整体全局状态以对象树的方式存放于单个 store。应用的整体全局状态以对象树的方式存放于单个 store。 唯一改变状态树(state tree)的方法是创建 action,一个描述发生了什么的对象,并将其 dispatch 给 store。 要指定状态树如何响应 action 来进行更新,你可以编写纯 reducer 函数,这些函数根据旧 state 和 action 来计算新 state。

Redux 提供的模式和工具使您更容易理解应用程序中的状态何时、何地、为什么以及如何更新,以及当这些更改发生时您的应用程序逻辑将如何表现. Redux 指导您编写可预测和可测试的代码,这有助于让您确信您的应用程序将按预期工作。

4、示例

import { createStore } from 'redux'

/**

* This is a reducer - a function that takes a current state value and an

* action object describing "what happened", and returns a new state value.

* A reducer's function signature is: (state, action) => newState

*

* The Redux state should contain only plain JS objects, arrays, and primitives.

* The root state value is usually an object.  It's important that you should

* not mutate the state object, but return a new object if the state changes.

*

* You can use any conditional logic you want in a reducer. In this example,

* we use a switch statement, but it's not required.

*/

function counterReducer(state = { value: 0 }, action) {

  switch (action.type) {

    case 'counter/incremented':

      return { value: state.value + 1 }

    case 'counter/decremented':

      return { value: state.value - 1 }

    default:

      return state

  }

}

// Create a Redux store holding the state of your app.

// Its API is { subscribe, dispatch, getState }.

let store = createStore(counterReducer)

// You can use subscribe() to update the UI in response to state changes.

// Normally you'd use a view binding library (e.g. React Redux) rather than subscribe() directly.

// There may be additional use cases where it's helpful to subscribe as well.

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: 'counter/incremented' })

// {value: 1}

store.dispatch({ type: 'counter/incremented' })

// {value: 2}

store.dispatch({ type: 'counter/decremented' })

// {value: 1}

复制代码

你需要使用 action 这个普通对象来描述发生了什么,而不是直接改变 state。然后,编写一个名为 reducer 的特殊函数,来决定如何基于 action 来更新整个应用的状态树。

(二)Reducer

1、作用

reducer是把 action 和 state 串起来;

翻译过来是减速器(处理State的过程)

2、用法

reducer 只是一个接收 state 和 action,并返回新的 state 的函数

reducer 可以嵌套调用

3、示例

//这俩是两个Reducer

function visibilityFilter(state = 'SHOW_ALL', action) {

  if (action.type === 'SET_VISIBILITY_FILTER') {

    return action.filter

  } else {

    return state

  }

}

function todos(state = [], action) {

  switch (action.type) {

    case 'ADD_TODO':

      return state.concat([{ text: action.text, completed: false }])

    case 'TOGGLE_TODO':

      return state.map((todo, index) =>

        action.index === index

          ? { text: todo.text, completed: !todo.completed }

          : todo

      )

    default:

      return state

  }

}

复制代码

再开发一个 reducer 调用这两个 reducer,进而来管理整个应用的 state:

function todoApp(state = {}, action) {

  return {

    todos: todos(state.todos, action),

    visibilityFilter: visibilityFilter(state.visibilityFilter, action)

  }

}

复制代码

这差不多就是 Redux 思想的全部。注意到没我们还没有使用任何 Redux 的 API。Redux 里有一些工具来简化这种模式,但是主要的想法是如何根据这些 action 对象来更新 state,而且 90% 的代码都是纯 JavaScript

(三)API

1、createStore

创建一个 Redux store 来以存放应用中所有的 state。

应用中不要创建多个 store

2、Store

Store 就是用来维持应用所有的 state 树 的一个对象。 改变 store 内 state 的惟一途径是对它 dispatch 一个 action。

getState()返回应用当前的 state 树。

dispatch(action)分发 action。这是触发 state 变化的惟一途径。

subscribe(listener)添加一个变化监听器。每当 dispatch action 的时候就会执行,state 树中的一部分可能已经变化。

replaceReducer(nextReducer)

3、 combineReducers

combineReducers 辅助函数的作用是,把一个由多个不同 reducer 函数作为 value 的 object,合并成一个最终的 reducer 函数,然后就可以对这个 reducer 调用 createStore 方法。

4、applyMiddleware(...middleware)

使用包含自定义功能的 middleware 来扩展 Redux 是一种推荐的方式。Middleware 可以让你包装 store 的 dispatch 方法来达到你想要的目的。同时, middleware 还拥有“可组合”这一关键特性。多个 middleware 可以被组合到一起使用,形成 middleware 链。其中,每个 middleware 都不需要关心链中它前后的 middleware 的任何信息。

5、compose

从右到左来组合多个函数。

这是函数式编程中的方法,为了方便,被放到了 Redux 里。

当需要把多个 store 增强器 依次执行的时候,需要用到它。

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容