Recursive Component 是什麼?

React Component 是個 function 所以當然也可以用 Recursion,如果不知道 Recursion(遞迴) 的朋友這邊簡單的介紹一下

Recursion (遞迴) 一個 function 呼叫自己,每個 recursive function 都需要有

  • base case: 一但此狀態達成,就不再呼叫遞迴函式
  • recursive case: 在此狀態下,持續呼叫遞迴函式

$n!$ (factorial function):在數學裡的意思是將到 n 數值乘再一起, ex: $$4! = 4 \times 3 \times 2 \times 1$$ ,在程式裡面我們習慣將其稱作 $fact(n)$

$$fact(1) = 1$$

$$fact(2) = 2 \times 1$$

$$fact(3) = 3 \times 2 \times 1$$

$$fact(4) = 4 \times 3 \times 2 \times 1$$

$$fact(5) = 5 \times 4 \times 3 \times 2 \times 1$$

所以將它換成

$$fact(1) = 1$$

$$fact(2) = 2 \times fact(1)$$

$$fact(3) = 3 \times fact(2)$$

$$fact(4) = 4 \times fact(3)$$

$$fact(5) = 5 \times fact(4)$$

所以

$$fact(n) = n \times fact(n - 1)$$

我們實做看看 fact function

function fact (num) {
if (num === 1) return 1;

return num * fact(num - 1);
}

其他還有費波那契數列(Fibonacci Sequence)、考拉茲猜想(The Collaztz conjecture) 都會用到遞迴的概念

進入正題

這種 Component 通常被用來 Render 樹狀的資料,比如說可以在別人的留言上留言,或者是巢狀的側邊導覽 Bar 等等都可以用 Recursive Component 來實作

這邊是我們的資料,可以看到一個留言下有多個留言的樹狀資料結構

class CommentModel {
constructor(username, content = "", subComments = [], id = uuid()) {
this.id = id;
this.username = username;
this.content = content;
this.subComments = subComments;
}
}

const comments = [
new CommentModel("Brian", "I think this is really cool!", [
new CommentModel("Emily", "Yea, I agree 😀", [
new CommentModel("Kevin", "What make you guys think that way ???")
]),
new CommentModel("Miranda", "Well, at least we have some progress", [
new CommentModel("Haha", "No!!!!!!")
])
])
];

這邊我們的 RecursiveComment 就是一個遞回函式,然後會停止遞迴的狀態就是都當沒有任何子留言的時候

const RecursiveComment = ({ id, username, content, subComments }) => {
return (
<div class="comment" key={id}>
<div class="comment-title">{username}</div>
<div class="comment-content">{content}</div>
<div class="sub-comment">
{subComments.map((comment) => (
<RecursiveComment {...comment} />
))}
</div>
</div>
);
};

export default function Post() {
return (
<div className="Post">
<h1>This is the post about recursive component</h1>
<p class="post-content">
So a recursvie component is a component render itself as a tree
</p>
<div class="comment-section-title">Comments</div>
<hr />
{comments.map((comment) => (
<RecursiveComment {...comment} />
))}
</div>
);
}

成果

Image.png

結語

Recursive Component 是的 usecase 較少,且閱讀性較差,所以大部分的情況,只適用於需要動態樹狀資料結構才有可能需要 Recursive Component,但若是靜態畫面的話,其實使用一般元件搭配 Composition 或者 Compound Component 等元件設計模式,元件會更容易閱讀、維護

建立 React Web 和 React Native 的 Monorepo
Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×