一時興起...??
我寫下了以下代碼
import React, { useRef } from 'react';
import { useHistory } from 'react-router-dom';
// Parent component
const Example: React.FC = () => {
// Case A:
const packHistoryToRef = useRef<ReturnType<typeof useHistory>>(useHistory());
// Case B:
const history = useHistory();
console.log(packHistoryToRef); // It works!??
return (
[1, 2, 3, 4, 5].map(i => (
// Case A solution
<Child history={packHistoryToRef} />
// Case B solution
<Child history={history} />
))
)
}
// Child component
const Child = ({ history }) => {
// Case A: Is `history` object point to the same memory address?
// Case B: There’s five printouts here. Does that mean it’s gonna repeat it five times?
console.log(history, 'history')
}
我這樣使用安全嗎?
否則,我認為這是這樣做的好處是
- 節省記憶體
- 清除
- 它在子組件中非常有用(尤其是在 ListItem 中)
uj5u.com熱心網友回復:
是否可以將 useHistory 用作 useRef 的值
是的,你可以將任何你喜歡的值存盤到 React ref 中。
之所以useRef(useHistory())有效是因為它仍然遵循鉤子的規則。
它相當于:
const history = useHistory();
const packHistoryToRef = useRef(history);
鉤子以相同的順序,無條件地,在每個渲染周期中呼叫。
可以
節省記憶體
我想它保存了一個變數宣告。不多了。
清除
對我或其他熟悉 javascript、React 和 React 鉤子的人來說,這似乎很清楚。盡管通常最好更明確地說明您的代碼在做什么,而不是試圖“花哨”。
它在子組件中非常有用(尤其是在 ListItem 中)
我不會說它比
history首先明確宣告物件更有用。
我建議堅持撰寫更清晰易讀的代碼,每一行都有特定的目的。
const history = useHistory(); // (1) define history
const historyRef = useRef(history); // (2) save ref
更新
// Parent component const Example: React.FC = () => { // Case A: const packHistoryToRef = useRef<ReturnType<typeof useHistory>>(useHistory()); // Case B: const history = useHistory(); console.log(packHistoryToRef); // It works!?? return ( [1, 2, 3, 4, 5].map(i => ( // Case A solution <Child history={packHistoryToRef} /> // Case B solution <Child history={history} /> )) ) }
正如我在評論中指出的那樣,鉤子history提供的物件useHistory基本上已經是對單一歷史實體的參考,因此將它存盤在您自己的 React ref 中不會提供任何額外的好處。只是傳下去history從useHistory兒童的組件。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/352336.html
標籤:javascript 反应 打字稿 反应路由器 反应路由器dom
下一篇:獲取所選表格單元格的“資料”值
