反应自定义钩子useState初始化值不会通过外部道具更新

问题描述

我有一个使用useState的自定义钩子,该钩子具有语言环境状态值,并且我从外部props设置了初始值,但是当我的props改变时,我的内部状态值没有得到更新。我不太了解,每次触发该组件或应用程序生命周期中有多少个自定义钩子实例?

这是代码示例:

// custom hook
const useCustomHook = (initValue) => {
   const [isFetching,setIsFetching] = useState(initValue);

   useEffect(() => {
      console.log('initValue :>> ',initValue,',isFetching :>>',isFetching);
   },[initValue,isFetching);
}
// component
const myComponent = (props) => {
   const [shouldTrigger,setShouldTrigger] = useState(false);

   useCustomHook(shouldTrigger);

   onButtonClick = () => {
     setShouldTrigger(true);
   }
}

这是我得到的控制台日志,

// when my component mouts
'initValue :>> ',false,false
// when button clicked
'initValue :>> ',true,false

如您所见,只要我从主组件将shouldTrigger设置为true,就会调用我的自定义钩子,但是,自定义钩子值中的本地状态值isFetching仍然是错误,是不是真的,因为每次都会从外部道具分配它?我上面的两个useCustomHook是相同实例还是不同实例?如果要调用其他实例,为什么第二个实例不将初始值设置为“ true”?

这是代码链接 https://stackblitz.com/edit/react-yma5my?file=index.js

解决方法

  1. 我不确定,但是我认为这是因为如果使用useState,则只能定义一次此值。
  2. and is my above two useCustomHook the same instance or different他们会有所不同。

您可以将代码重写为

// custom hook
const useCustomHook = (initValue) => {
   const [isFetching,setIsFetching] = useState(initValue);

   useEffect(() => {
      console.log('initValue :>> ',initValue,',isFetching :>>',isFetching);
   },[initValue,isFetching);
  return [isFetching,setIsFetching]
}
// component
const myComponent = (props) => {
   const [isFetching,setIsFetching] = useCustomHook(false);

   onButtonClick = () => {
     setIsFetching(true);
   }
}

更新

我只是一个想法,如何从一开始就以自己想要的风格进行写作,但是我的第一个建议仍然更好(如我所想)

// custom hook
const useCustomHook = (value) => {
   const [isFetching,setIsFetching] = useState(value);

   useEffect(() => {
     setIsFetching(value);
   },[value]);

   useEffect(() => {
      console.log('value :>> ',value,isFetching);
}
// component
const myComponent = (props) => {
   const [shouldTrigger,setShouldTrigger] = useState(false);

   useCustomHook(shouldTrigger);

   onButtonClick = () => {
     setShouldTrigger(true);
   }
}

它会引起setState的额外调用,但会基于输入道具实现状态更新;

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...