问题描述
useCustomHook()=>{
const [state,setState] = React.useState(0);
const modifyState = ({state,n}) => {setState(state + n);}
/*Does state need to be included as an argument/parameter here in modifyState? If,alternatively,const modifyState = ({n}) => {setState(state + n)};
Will state always be 0 in the scope of modifyState,since that was its value when the function was
created originally. So everytime modifyState is called,it is equivalent to (n)=>setState(0+n) ?
*/
return [state,modifyState];
}
const FunctionalComponent = () => {
const [state,modifyState] = useCustomHook();
const n = 5;
modifyState({state,n}) /* Does state need to be passed here? (since useCustomHook already has its own
copy of state) */
//... logic ....
return <div></div>
}
通过在控制台中进行一些测试,似乎不需要将 state
作为参数传递给 modifyState
。但是,我对这背后的范围逻辑感到困惑,并且不确定行为挂钩是否会改变它。有人能解释一下这背后的逻辑吗?
解决方法
您可以使用 setState
的函数实现来代替传递状态。像这样:
const modifyState = (n) => {
setState(state => state + n);
}
参考:https://reactjs.org/docs/hooks-reference.html#functional-updates