[英]How to call a Function which is called inside Reducer, and the said Function uses the State returned by useReducer?
React v17反应 v17
I am using useReducer
.我正在使用useReducer
。 In the reducer function , I need to call another function check for network fetch.在减速器 function中,我需要调用另一个 function检查网络获取。 In check( ) , I need to access the state
, which is returned by useReducer
.在check()中,我需要访问由state
返回的useReducer
。
I am getting this error can't access lexical declaration 'value' before initialization
.我收到此错误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
)
I have made aCodeSandBox for explanation purpose.我制作了一个CodeSandBox用于解释目的。
What is the efficient way to restructure the code?重构代码的有效方法是什么?
A. Should I need to call check from outside the useReducer
? A. 我是否需要从useReducer
外部调用check ? To do that, I think I will need to use useEffect
.为此,我想我需要使用useEffect
。
B. I declared check outside of the functional component as a let
variable, and defined it after reducer function , but it was not working correctly and state
was getting changed more than once. B. 我将功能组件之外的check声明为let
变量,并在减速器 function之后定义它,但它无法正常工作,并且state
被多次更改。
C. C。 Some better approach which I am unable to find out?一些我无法找到的更好的方法?
The reducer should be responsible for merging/reducing state and that is all.减速器应该负责合并/减少 state 仅此而已。
As someone in your question comments said, there should not be any side effectw in reducer (only state manipulations).正如您问题评论中的某人所说,减速器中不应该有任何副作用(仅 state 操作)。 So change the state in the reducer and check the counter state by using useEffect
and dependency variables .因此,更改减速器中的 state 并使用useEffect
和依赖变量检查计数器state 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.