javascript useState将错误的值用于自定义挂接

jslywgbw  于 2022-12-21  发布在  Java
关注(0)|答案(2)|浏览(146)

在我的React组件中,我有以下代码:

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

这是我的自定义钩子:

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

当我将roomTypenull修改为一个值时,它记录'executing useAdditionalGuestAmounts hook',然后记录'returning array',但是additionalGuestAmounts的值没有更新;它仍然是一个空数组。2为什么在执行自定义钩子的时候这个值没有被更新呢?

l7wslrjt

l7wslrjt1#

useState钩子中传递的值只是状态的初始值,如useState钩子文档中所述:https://reactjs.org/docs/hooks-state.html,为了确保在调用useAdditionalGuestAmounts钩子时更新状态,我们必须使用新值调用setAdditionalGuestAmounts

// 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'
            },
        ])
    }

如果您需要在页面加载时调用useAdditionalGuestAmounts,则可以使用useEffect钩子(https://reactjs.org/docs/hooks-effect.html

oaxa6hgo

oaxa6hgo2#

修改roomTypeId时,不会更新additionalGuestAmounts状态变量的值,因为不会再次调用useAdditionalGuestAmounts挂接。这是因为useAdditionalGuestAmounts挂接仅在首次呈现组件时调用,并且不会再次调用。
正如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;
};

您还需要将occupantsForBaseRate参数添加到dependencies数组中,因为useAdditionalGuestAmounts挂钩依赖于它。
希望这个有用。

相关问题