javascript - 什么是纯 reducer ?

标签 javascript reactjs

我的理解是有一个“纯函数”的概念,我在这个 video 中得到了解释。还有这个问题What is pure functions?

但是,我在 this link 上阅读的 flux/redux 上下文中遇到了术语“Pure reducers”

但我不完全确定如何将这个“纯概念”应用到 reducer 上,什么是纯 reducer?

最佳答案

这是我的理解,就 redux 而言,reducer 是一个接受两个参数(状态、 Action )的函数。

 1. state represents the current state of the application in store
 2. action represents the action that triggered

Redux 假定 reducer 确实接受当前状态并且不改变状态但返回新状态,具体取决于操作类型。如果它坚持并且不改变状态,那么它就是一个纯粹的 reducer 。

/************************* 一个纯reducer的例子****************** **********/

 var initialState = {counter:0};
 function counterReducer(state = initialState, action){
     if (action.type === 'INCREMENT'){
         // returns a new state incrementing a counter
         return {counter:state.counter + 1};
     }
     else if (action.type === 'DECREMENT'){
         // return a new state decrementing a counter
        return {counter:state.counter - 1};
     }

     //  returns the state as is
     return state;
 }

上面的函数没有副作用,只要用相同的参数集调用它,它总是返回相同的输出。

/********************* 不纯还原剂的例子 ******************** *******/

var initialState = {counter:0};
 function counterReducer(state = initialState, action){
     if (action.type === 'INCREMENT'){
         // modifies state by mutating or incrementing the counter in state
         state.counter++;
     }
     else if (action.type === 'DECREMENT'){
         // modifies state by mutating or decrementing the counter in state
        state.counter--;
     }

     //  returns the state
     return state;
 }

关于javascript - 什么是纯 reducer ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37455185/

相关文章:

javascript - 文件上传: Check for file format and then invoke srvlet

javascript - 小叶杂食+聚类标记+过滤标记聚类组

CSS 模块嵌套选择器

javascript - react sibling 的通信,只能访问 parent

javascript - 当在选项上设置 header 时,获取 POST 内容类型不会更改

css - 在带有 sass、css 和语义 ui 的 nextjs 中使用谷歌字体使用react

javascript - 如何使用 Material UI 默认组件

javascript - 在 React.js 中循环并渲染一个对象

javascript - 带有 iframe 的邮政编码检查器结合 Javascript

javascript - 在WebView中执行JS脚本