有一個接收道具的組件。
props 有一個陣列的形狀,對于這個陣列的每個元素,一個函式將回傳一個不同的組件來渲染。
function MainComponent ({ data }) => { // data is props, an array
const specialFunction = (index) => {
switch (index) {
case 0:
return <Component0 />;
case 1:
return <Component1 />;
case 2:
return <Component2 />;
default:
return null;
}
};
...
return (
...
data.map((item, index) => {
... // do other stuff with item
<div>{specialFunction(index)}</div> // the function that we talk about
...
);
如果道具不會改變,有沒有辦法記住這個結果?或者有什么更好的寫法?
uj5u.com熱心網友回復:
帶有空依賴陣列的useCallback將是這里最好的方法。useCallback 將回傳回呼的記憶版本,該版本僅在依賴項之一發生更改時才會更改。由于我們的依賴陣列是[]它只會執行一次并且函式將被記憶。
const specialFunction = useCallback((index) => {
switch (index) {
case 0:
return <Component0 />;
case 1:
return <Component1 />;
case 2:
return <Component2 />;
default:
return null;
}
}, []);
uj5u.com熱心網友回復:
有幾種方法可以實作這一點:
- 您可以使用狀態來存盤陣列
const [components] = useState([<Component0 />, <Component1 />, <Component2 />])
然后components[index]在嘗試渲染時使用。
- 您可以嘗試記住
useCallback您的功能。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/355924.html
標籤:javascript 反应 打字稿 反应钩子 反应使用备忘录
上一篇:如何跨多個dyno實作快取
