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

React custom hook useState initialization value not update through outside props

我有一个自定义挂钩,它使用 useState 具有区域设置值,我从外部道具设置初始值,但是当我的道具改变时,我的内部状态值没有得到更新,另外我不太明白,每次触发时我的组件或应用程序生命周期中有多少个自定义挂钩实例?

代码示例如下:

// 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, ', isFetching :>>', false
// when button clicked
'initValue :>> ', true, ', isFetching :>>', false

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

这是代码link 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 :>>', isFetching);
   }, [initValue, isFetching);
}
// component
const myComponent = (props) => {
   const [shouldTrigger, setShouldTrigger] = useState(false);

   useCustomHook(shouldTrigger);

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

它会导致额外调用 setState 但会根据输入道具实现状态更新;