简体   繁体   English

自定义 React Hooks 以及在 useEffect 挂钩中保留的内容

[英]Custom React Hooks and what to keep inside useEffect hook

I have the following code and I wonder how I can improve performance, specifically, should I move the const fuse = new Fuse... section and the buildSearchRequest function within useEffect so it is called only when the search query is changed?我有以下代码,我想知道如何提高性能,具体来说,我应该移动const fuse = new Fuse...部分和buildSearchRequest中的 buildSearchRequest function 以便仅在更改搜索查询时调用它? I have noticed my code that consumes the custom hooks hits the new Fuse section many times.我注意到我的使用自定义钩子的代码多次点击new Fuse部分。


    const [searchResults, setSearchResults] = React.useState([])
    const fuse = new Fuse(DummySearchResponse.results, {
        keys: ["data.programmeTitle"],
        includeScore: true,
        threshold: 0.2,
    })
    const searchApiUrlStart = "http://mimir.prd.oasvc.itv.com/search?query="
    const searchApiUrlEnd =
        "&entityType=programme&streamingPlatform=itv_hub&checkAvailability=true"

    const buildSearchRequest = (searchString) => {
        return (
            searchApiUrlStart +
            encodeURIComponent(searchString) +
            searchApiUrlEnd
        )
    }

    React.useEffect(() => {
        if (!query) return

        const fetchData = async () => {
            let searchData
            if (useLiveSearchApi) {
                const liveResponse = await fetch(
                    "http://mimir.prd.oasvc.itv.com/search?query=" +
                        buildSearchRequest(query) +
                        "&entityType=programme&streamingPlatform=itv_hub&checkAvailability=true"
                )

                const liveJson = await liveResponse.json()
                const liveResults = await liveJson.results
                searchData = liveResults

            } else {
                const fuseResponse = await fuse.search(query)
                const fuseJson = await fuseResponse.map((result) => {
                    return result.item
                })
                searchData = fuseJson
            }

            const mappedResults = await searchData.map((searchItem) => ({
                title: searchItem.data.programmeTitle,
                contentImageUrl: searchItem.data.imageHref,
                programmeCCId: searchItem.data.programmeCCId,
                episodeId: searchItem.data.episodeId,
            }))

            setSearchResults(mappedResults)
        }

        fetchData()
    }, [query])

    return { searchResults }
}```

First and foremost, avoid declaring a callback within the useEffect.首先,避免在 useEffect 中声明回调。 What you need to do is use the useCallBack hook to declare your fetchData callBack您需要做的是使用 useCallBack 挂钩来声明您的 fetchData callBack

Your code should atleast look like...你的代码至少应该看起来像......

const fetchData = useCallBack(() => {
    // Your Fetch Data Code

}, [<dependency array>]) // Here, you want to add all dependencies whose current state you need. Note that if a dependency is not added here, and you use it within the useCallBack, you'll only access a stale state (state during initialization), and never the updated dependency state.

// Here are three ways you can declare your useEffect
useEffect(fetchData, [query]); You probably wanna use this one. Less lines and much cleaner.

useEffect(() => fetchData(), [query]);

useEffect(() => {
    fetchData();
}, [query]);

Your useEffect will only be called once the query variable has been updated.只有在更新query变量后才会调用您的 useEffect。 So, to ensure a sideEffect is not triggered, ensure your useEffect or the useCallBack specified as the trigger does not update the variable.因此,为确保不触发 sideEffect,请确保您的 useEffect 或指定为触发器的 useCallBack 不会更新变量。 If this is the case, your code will be stuck in an indefinite loop.如果是这种情况,您的代码将陷入无限循环。

暂无
暂无

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

相关问题 是否可以在 React 的 useEffect 中使用自定义挂钩? - Is it possible to use a custom hook inside useEffect in React? 在 useEffect 内反应钩子 updateState - react hooks updateState inside useEffect React Hooks:数组未在 useEffect Hook 中更新/更改 - React Hooks: array not updating/changing in useEffect Hook React hooks:什么/为什么`useEffect`? - React hooks: What/Why `useEffect`? 自定义挂钩 useEffect 内的 React setState 调用未更新 state - React setState call inside a custom hook useEffect is not updating the state 自定义挂钩内的 useEffect 未在 React 中以正确的顺序调用 - useEffect inside custom hook not getting called in correct oreder in React 在自定义钩子和组件中使用 useEffect 有什么区别 - what is the difference between using useEffect inside a custom hook and a component 无效的钩子调用。 Hooks 只能在 react 函数组件内部使用... useEffect, redux - Invalid hook call. Hooks can only be used inside of a react function component... useEffect, redux 反应 useEffect 无效的钩子调用。 钩子只能在 function 组件的主体内部调用 - React useEffect Invalid hook call. Hooks can only be called inside of the body of a function component React Hooks:确保useEffect仅在自定义挂钩的数组参数的内容更改时运行的惯用方式 - React Hooks: Idiomatic way to ensure that useEffect runs only when the contents of an array argument to the custom hook change
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM