在自定义钩子的函数内部使用 React 状态背后的范围逻辑是什么?

问题描述

假设您有一个自定义钩子:

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

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...