【问题标题】:Avoid infinite loop on React - useState避免 React 上的无限循环 - useState
【发布时间】:2023-02-05 11:47:51
【问题描述】:

如何放置导出的函数(在上下文中)并在 useEffect 中接收参数,以便该函数中的 setState 不会导致无限重新渲染。

功能:

export const PokemonProvider = ({children} : {children: ReactNode}) => {
    const [pokemon, setPokemon] = useLocalStorage<Pokemon[]>('pokemon', [{id: 123, name: 'mariomon', type: 'fogo', imageUrl: 'www.google.com'}]);

    const getPokemon = (newlyPokemon : Pokemon | null) => {
        newlyPokemon && setPokemon(prevState => [...prevState, newlyPokemon]);
    };

    return <PokemonContext.Provider value={{getPokemon, pokemon}}>
        {children}
    </PokemonContext.Provider>
}

getPokemon 可能是这里的问题,即使我对 React 的了解有限,如果我使用 useCallback 例如如何访问 newPokemon?我应该使用 useRef 并在 getPokemon 上为它分配 newPokemon 值,然后在 useEffect 中为它分配 setPokemon 吗?

需要帮助,谢谢!

【问题讨论】:

    标签: reactjs react-hooks react-tsx


    【解决方案1】:

    useCallback 不关心你的回调有多少参数,因为这不会改变函数存储的位置。

    提供的代码中没有useEffect

    如果 useLocalStorage 钩子以正确的方式编写,它的 setter 函数应该已经包装在 useCallback 中,因此它的内存位置永远不会改变。

    当您将 getPokemon 包装在 useCallback 中时,它唯一的依赖项是 setPokemon

    const getPokemon = useCallback((newlyPokemon : Pokemon | null) => {
      newlyPokemon && setPokemon(prevState => [...prevState, newlyPokemon]);
    }, [setPokemon]);
    

    如果您担心重新渲染,请查看状态管理器以控制重新渲染哪些元素,因为对 pokemon 的任何更改都会导致 PokemonProvider 的每个子元素重新渲染

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-02-21
      • 1970-01-01
      • 2021-05-17
      • 2019-05-01
      • 2022-01-15
      • 2021-10-05
      • 2021-01-06
      相关资源
      最近更新 更多