簡體   English   中英

避免使用反應鈎子重新渲染

[英]Avoid re render with react hooks

我有一些通過 props 來自 Redux 的值,當這個值改變時,我不想再次渲染組件。

我找到了一些答案,說我可以使用 Memo,但我不知道這是否是我的最佳選擇?

我的“代碼”:

const MyComponent = () => {
    return ...;
}

const mapStateToProps = state => ({
  myVar: state.myVar
});

export default connect(mapStateToProps)(MyComponent);

在這種情況下,更改myVar不應重新渲染組件。

React.memo 可以完成這項工作,你可以傳遞一個自定義的相等檢查函數來執行重新渲染,只有當它返回一個假值時。 我從未遇到過您想完全忽略 Redux 存儲中的值更新的情況,也許它不應該存儲在那里?

備忘錄 API

例如: React.memo(Component, [areEqual(prevProps, nextProps)])

使用選擇器 API

另一種方法是將useSelector與自定義相等檢查函數一起使用:

useSelector Redux API 參考

連接API

如果你仍然想堅持使用 mapStateToProps,你也可以傳遞一個自定義的相等性檢查函數作為 connect 函數的參數:

areStatePropsEqual Redux API 參考

編輯:useRef 解決方案

通過使用 useRef,您可以存儲一個可變變量,該變量將在組件的整個生命周期內保持不變。

基於您的示例:

const StoreMyVar = (WrappedComponent) => ({myVar, ...props}) => {
  const myRefVar = useRef(myVar)
  return <WrappedComponent myVar={myRefVar} {...props} />
}

const MyComponentWithImmutableVar = StoreMyVar(MyComponent)

最快的方法是React.memo ,但您可以僅將其與功能組件一起使用。 小心,它沒有經過測試。

const MyComponent(props) {
  return ...;
}

const areEqual(prevProps, nextProps) {
  return prevProps.myVar === nextProps.myvar
}

const mapStateToProps = state => ({
   myVar: state.myVar
});

export default React.memo(MyComponent, areEqual);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM