简体   繁体   English

useState 在自定义挂钩中使用了错误的值

[英]useState is using the wrong value with a custom hook

In my React component, I have the following code:在我的 React 组件中,我有以下代码:

const [additionalGuestAmounts] = useState<RatePlan['additionalGuestAmounts']>(
  useAdditionalGuestAmounts(roomType, occupantsForBaseRate)
)

And here is my custom hook:这是我的自定义挂钩:

const useAdditionalGuestAmounts = (
  roomType: RoomType,
  occupantsForBaseRate: number
): RatePlan['additionalGuestAmounts'] => {
  console.log('executing useAdditionalGuestAmounts hook')
  if (!roomType) {
    return []
  }
  console.log('returning array')
  return [
    {
      foo: 'bar'
    },
  ]
}

When I modify roomType from null to a value, it logs 'executing useAdditionalGuestAmounts hook' and then 'returning array' , however the value of additionalGuestAmounts is not updated;当我将roomTypenull修改为一个值时,它会记录'executing useAdditionalGuestAmounts hook'然后'returning array' ,但是additionalGuestAmounts的值没有更新; it stays as an empty array.它保持为一个空数组。 Why is the value not being updated if the custom hook is being executed?如果正在执行自定义挂钩,为什么不更新该值?

The value that is passed in the useState hook is only the initial value of the state as explained on the documentation of the useState hook: https://reactjs.org/docs/hooks-state.html , to make sure that the state is updated whenever the useAdditionalGuestAmounts hook is called we will have to call setAdditionalGuestAmounts with the new value. useState钩子中传递的值只是状态的初始值,如 useState 钩子的文档中所述: https ://reactjs.org/docs/hooks-state.html ,以确保状态是每当调用 useAdditionalGuestAmounts 挂钩时都会更新,我们将不得不使用新值调用setAdditionalGuestAmounts This would then look like:这看起来像:

    // Initial state
    const [additionalGuestAmounts, setAdditionalGuestAmounts] = useState<RatePlan['additionalGuestAmounts']>([])
    const useAdditionalGuestAmounts = (
        roomType: RoomType,
        occupantsForBaseRate: number
    ) => {
        if (!roomType) {
            return []
        }
 
        // Update the state, this causes the page to re-render
        setAdditionalGuestAmounts( [
            {
                foo: 'bar'
            },
        ])
    }

If you need the useAdditionalGuestAmounts to be called on page load you can use the useEffect hook for this ( https://reactjs.org/docs/hooks-effect.html )如果您需要在页面加载时调用useAdditionalGuestAmounts ,您可以为此使用useEffect挂钩( https://reactjs.org/docs/hooks-effect.html

The value of the additionalGuestAmounts state variable is not being updated when you modify roomTypeId because the useAdditionalGuestAmounts hook is not being called again.当您修改 roomTypeId 时,additionalGuestAmounts 状态变量的值不会更新,因为不会再次调用 useAdditionalGuestAmounts 挂钩。 This is because the useAdditionalGuestAmounts hook is only called when the component is first rendered, and is not called again.这是因为 useAdditionalGuestAmounts 挂钩只在组件首次渲染时调用,不会再次调用。

As stated previously by rowan, you can a useEffect hook inside the useAdditionalGuestAmounts hook.正如 rowan 之前所述,您可以在 useAdditionalGuestAmounts 挂钩内使用一个 useEffect 挂钩。

const useAdditionalGuestAmounts = (
  roomType: RoomType,
  occupantsForBaseRate: number
): RatePlan['additionalGuestAmounts'] => {
  console.log('executing useAdditionalGuestAmounts hook')
  const [additionalGuestAmounts, setAdditionalGuestAmounts] = useState<
    RatePlan['additionalGuestAmounts']
  >([]);

  useEffect(() => {
    if (!roomType) {
      return;
    }
    console.log('returning array');
    setAdditionalGuestAmounts([
      {
        foo: 'bar',
      },
      {
        foo: 'bar',
      },
      {
        foo: 'bar',
      },
      {
        foo: 'bar',
      },
      {
        foo: 'bar',
      },
    ]);
  }, [roomTypeId, occupantsForBaseRate]);

  return additionalGuestAmounts;
};

You also need to add the occupantsForBaseRate argument to the dependencies array, because the useAdditionalGuestAmounts hook depends on it.您还需要将 occupantsForBaseRate 参数添加到 dependencies 数组,因为 useAdditionalGuestAmounts 挂钩依赖于它。

Hope this helps.希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM