【问题标题】:React.memo with react-router-dom useLocation()React.memo 与 react-router-dom useLocation()
【发布时间】:2021-03-08 14:24:25
【问题描述】:

最近我发现我的 React 应用程序存在一些性能问题,经过一些研究我发现了 React Memo。一些训练示例作为例外工作,但是当将其连接到我的应用程序时,它没有任何效果。我发现问题出在 useLocation 上。

const Table = React.memo(() => {
 
    const location = useLocation();

    return <div>something</div>
    
},(prevProps, nextProps) => {
    return true //I dont want re-render this Component when parent component is re-rendered
}) 

没有 useLocation 它可以工作,但我需要这个位置,因为基于这个位置,更具体地说,基于来自这个位置的过滤器,我调用 API 数据。 类似的东西

const location = useLocation();
  useEffect(() => {
    dispatch(getData(location.search))
}, [location]);

有更好的解决方案或提示吗?

【问题讨论】:

    标签: reactjs react-router-dom react-memo


    【解决方案1】:

    解决方案是创建一个包装器,将位置作为道具传递。这样做会使 table 成为一个纯组件,并且只会在位置更改时重新渲染。

    function TableWrapper(){
      const location = useLocation()
    
      return <Table location={location} />
    }
    

    那么表格需要有位置作为道具

    const Table = React.memo(({location}) => {
        return <div>something</div>
    }) 
    

    【讨论】:

      猜你喜欢
      • 2021-04-17
      • 2020-08-23
      • 1970-01-01
      • 2021-06-23
      • 2021-12-14
      • 2022-12-02
      • 1970-01-01
      • 2020-07-11
      • 2019-07-19
      相关资源
      最近更新 更多