如何使用React.memo()正确包装功能组件?仍然在每次重新渲染父组件时都重新渲染

时间:2020-02-18 13:16:56

标签: javascript reactjs react-native

缩短了代码,使其更具可读性。

在components / FunctionalComponent.js中:

import React, {memo} from 'react'
//other necessary imports...

const FunctionalComponent = ({destructuredProps}) => {
   ...
   //some code that determines what and how the component behaves. Uses destructured props.
   ...
   return (
   <View>
      ...
      A lot of other elements
      ...
   </View>
   )
}

export default memo(FunctionalComponent);

重要的是要注意,一些分解后的道具是回调函数,但是这些已经使用useCallback进行了记忆。

在main.js中:

import React from 'react'
import FunctionalComponent from 'components/FunctionalComponent'

const MainComponent = () => {
   //some code that determines how component behaves
   return (
   <View>
      //Some other components
      <FunctionalComponent />
   </View>
   )
}

export default MainComponent 

如何将这样的组件包装在memo()中以防止重新渲染?

  • 我正在FunctionalComponent内部使用'console.log('function rerendered')来查看何时重新渲染。

编辑:添加了更多详细信息

该组件是带有一些按钮和地图的自动完成的Google地图搜索栏。当我与不属于传递给搜索栏组件的props列表的一部分的屏幕上的元素进行交互时,它会重新呈现,因此可能是我使用了不正确的“ useCallback”。这就是组件的使用方式。

<AutoCompleteSearch
   term={searchTerm}
   onTermChange={setSearchTermCallBack}
   enabled = {isSearchBarEnabled}
   setResultDetail = {setResultDetailsCallBack}
/>

这是我定义回调和状态变量的方式:

const [searchTerm, setSearchTerm] = useState('');
const setSearchTermCallBack = useCallback((term)=>setSearchTerm(term),[]);

const [resultDetails, setResultDetails] = useState({});
const setResultDetailsCallBack = useCallback((term)=>setSearchTerm(term),[]);

搜索词和设置器将传递给组件,因为我需要API请求的信息。之所以通过详细信息设置程序,是因为我想访问和显示搜索栏中API调用返回的部分信息。

希望这使事情更清楚。

0 个答案:

没有答案