我有 tableRows 存盤在 useState 中的表組件。
我還有表格組件之外的搜索器組件。
當搜索器內部的資料發生變化時,tableRows 會在 useEffect 內部更新。
它運行良好,但會導致兩次重新渲染。我明白為什么。第一次因為 useSelector 重新渲染,第二次因為 useEffect 有 useSelector 值作為依賴。
但是如何避免一次重新渲染。我希望它在 tableRows 更改時重新呈現,而不是在搜索器更改時重新呈現。
const CatalogTable: React.FC<CatalogTableProps> = ({rows}) => {
const [tableRows, setTableRows] = React.useState(rows)
const searcher = useSelector(getTableSearcher, shallowEqual)
const getData = async () => {
const {data} = await CatalogService.getAllCatalogProducts({page: 1, searcher: searcher})
setTableRows(data.products)
}
React.useEffect(() => {
if(searcher)
getData()
}, [searcher])
return (
<>
<div className={styles.defaultTable}>
<Table
headers={headers}
label="Products catalog"
rows={tableRows}
total={total}
pagination
addButton
editButtons
searcher
getPage={(page: number) => nextPage(page)}
type='catalog'
/>
</div>
</>
)
}
export default CatalogTable
uj5u.com熱心網友回復:
一種可能的解決方案是記憶化:
const CatalogTable: React.FC<CatalogTableProps> = ({rows}) => {
const [tableRows, setTableRows] = React.useState(rows)
const searcher = useSelector(getTableSearcher, shallowEqual)
const getData = async () => {
const {data} = await CatalogService.getAllCatalogProducts({page: 1, searcher: searcher})
setTableRows(data.products)
}
React.useEffect(() => {
if(searcher)
getData()
}, [searcher])
const result = useMemo( () =>
<>
<div className={styles.defaultTable}>
<Table
headers={headers}
label="Products catalog"
rows={tableRows}
total={total}
pagination
addButton
editButtons
searcher
getPage={(page: number) => nextPage(page)}
type='catalog'
/>
</div>
</>, [tableRows]
);
return result;
}
export default CatalogTable
另一個解決方案是將 tableRows 和搜索查詢放在 redux 存盤中,并通過異步中間件同時更新它們。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/361214.html
標籤:javascript 反应 还原 使用效果 重新渲染
上一篇:檢查一個不存在的類
下一篇:嘗試匯入庫時出錯
