我正在使用React v17useReducer。在reducer 函式中,我需要呼叫另一個函式檢查網路獲取。在check()中,我需要訪問由 .state回傳的useReducer.
我收到此錯誤can't access lexical declaration 'value' before initialization。
const reducerFilterdValue = (state, action) => {
let newState ;
switch(action.type){
case 'increment':
if(check()===0){
newState={...state,counter:state.counter 1}
}
break;
default:
newState={...state}
break;
}
return newState;
}
const check=()=>{
return state.counter%2
}
const [state, dispatchValue] = useReducer(
reducerFilterdValue,
initialFilterdValue
)
我制作了一個CodeSandBox用于解釋目的。
重構代碼的有效方法是什么?
A. 我需要從外面打電話檢查useReducer嗎?為此,我想我需要使用useEffect.
B. 我將函陣列件之外的checklet宣告為變數,并在reducer function之后定義它,但它無法正常作業并且state多次更改。
C.一些我無法找到的更好的方法?
uj5u.com熱心網友回復:
減速器應該負責合并/減少狀態,僅此而已。
正如您問題評論中的某個人所說,減速器中不應該有任何副作用(只有狀態操作)。所以改變reducer中的狀態并通過使用和依賴變數檢查計數器狀態。useEffect
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/503697.html
標籤:javascript 反应 反应钩子 使用减少器
