如何解决在自定义钩子的函数内部使用 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
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。