我的理解是有一个“纯函数”的概念,我在这个 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/