[英]What is a pure reducer?
這是我的理解,就 redux 而言,reducer 是一個接受兩個參數(狀態、動作)的函數。
1. state represents the current state of the application in store
2. action represents the action that triggered
Redux 假設 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;
}
reducer 只是一個函數,它作為參數傳遞給數組的 reduce 函數。 例如:
const sumReducer = (acc, x) => acc + x
const multReducer = (acc, x) => acc * x
const sumResult = [1,2,3,4,5].reduce (sumReducer, 0)
const multResult = [1,2,3,4,5].reduce (multReducer, 1)
這基本上是一個減速器。
另一種形式的不純歸約器是在給定相同參數的情況下不返回相同值的歸約器。 所以使用 Dhananjaya Kuppu 的例子:
return {counter: state.counter + Math.floor(Math.random())}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.