gpt4 book ai didi

javascript - React 自定义 Hook 问题 - 无限依赖循环

转载 作者:行者123 更新时间:2023-11-30 19:18:32 25 4
gpt4 key购买 nike

我一直很喜欢陷入困境并处理现实世界中出现的所有有趣的新问题 :) 这是我遇到过几次的问题,很想看看你“应该”怎么做解决它!

概述:我创建了一个自定义 Hook 来封装我的应用程序的一些业务逻辑并存储我的一些状态。我在组件内使用该自定义 Hook 并在加载时触发事件。

问题是:我的 Hook 的loadItems 函数需要访问我的items 以获取最后一项的ID。将 items 添加到我的依赖项数组会导致无限循环。这是一个(简化的)示例:

简单的 ItemList 组件

//
// Simple functional component
//

import React, { useEffect } from 'react'
import useItems from '/path/to/custom/hooks/useItems'

const ItemList = () => {
const { items, loadItems } = useItems()

// On load, use our custom hook to fire off an API call
// NOTE: This is where the problem lies. Since in our hook (below)
// we rely on `items` to set some params for our API, when items changes
// `loadItems` will also change, firing off this `useEffect` call again.. and again :)
useEffect(() => {
loadItems()
}, [loadItems])

return (
<ul>
{items.map(item => <li>{item.text}</li>)}
</ul>
)
}

export default ItemList

自定义 useItems Hook

//
// Simple custom hook
//

import { useState, useCallback } from 'react'

const useItems = () => {
const [items, setItems] = useState([])

// NOTE: Part two of where the problem comes into play. Since I'm using `items`
// to grab the last item's id, I need to supply that as a dependency to the `loadItems`
// call per linting (and React docs) instructions. But of course, I'm setting items in
// this... so every time this is run it will also update.
const loadItems = useCallback(() => {
// Grab our last item
const lastItem = items[items.length - 1]
// Supply that item's id to our API so we can paginate
const params = {
itemsAfter: lastItem ? lastItem.id : nil
}
// Now hit our API and update our items
return Api.fetchItems(params).then(response => setItems(response.data))
}, [items])

return { items, loadItems }
}

export default useItems

代码中的注释应该指出问题所在,但我现在能想到的让 linters 满意的唯一解决方案是为 loadItems 调用提供参数(例如 loadItems({ itemsAfter: ... })) 其中,由于数据已经在此自定义 Hook 中,我真的希望不必在使用 loadItems 函数的任何地方都做。

非常感谢任何帮助!

迈克

最佳答案

如果您打算只运行一次效果,请忽略所有依赖项:

 useEffect(() => {
loadItems();
}, []);

关于javascript - React 自定义 Hook 问题 - 无限依赖循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57739169/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com