๐Ÿ‘ฉโ€๐Ÿ’ป/React

[React.js] Re-rendering Issue & Objects are not valid as a React child

ํ•œ๋‚˜ 2021. 3. 17. 14:38

์‹œ์ž‘ํ•˜๋ฉฐ

Nomad Coder ๊ฐ•์˜ ์ค‘ useTab ์ปค์Šคํ…€ ํ›… ๋งŒ๋“œ๋Š” ๊ณผ์ •์—์„œ ์ œ๋ชฉ์— ์จ๋‘” ๊ฒƒ์ฒ˜๋Ÿผ Re-rendering Issue์™€ Objects are not valid as a React ์ด์Šˆ๋ฅผ ๋งŒ๋‚ฌ๋‹ค. ํ”ํ•œ ์ด์Šˆ์ด๋ฏ€๋กœ ์ž‘์„ฑํ•˜๋ฉด์„œ ์ด๋Ÿฐ ์—๋Ÿฌ๊ฐ€ ์™œ ๋ฐœ์ƒํ–ˆ๋Š”์ง€ ์จ๋‘๊ณ ์ž ํ•œ๋‹ค.

์ฝ”๋“œ

import React, { useState } from "react";
const content = [
{
tab: "Section 1",
content: "I am the content of the section 1"
},
{
tab: "Section 2",
content: "I am the content of the section 2"
}
];
const useTabs = (initialTab, allTabs) => {
const [currentIndex, setCurrentIndex] = useState(initialTab);
if (!allTabs || !Array.isArray(allTabs)) { // (*1)
return;
}
return {
currentItem: allTabs[currentIndex],
changeItem: setCurrentIndex // (*2)
};
};
export default function App() {
const { currentItem, changeItem } = useTabs(0, content);
return (
<div className="App">
<h1>
Hello CodeSandbox{" "}
<span role="img" aria-label="eye emoji">
๐Ÿ‘€
</span>
</h1>
{content.map((section, index) => (
<button key={index} onClick={() => changeItem(index)}>
{section.tab}
</button>
))}
<div>{currentItem.content}</div> <!-- (*3) -->
</div>
);
}
view raw useTab.js hosted with โค by GitHub

Re-rendering Issue

์ •์ƒ์ ์œผ๋กœ ์ž‘๋™ํ•  ๋•Œ์˜ ์ฝ”๋“œ๋Š” ์œ„ ๋ชจ์Šต๊ณผ ๊ฐ™๋‹ค. ์—ฌ๊ธฐ์„œ 2๋ฒˆ ์ฃผ์„ ํ‘œ์‹œ์—์„œ ์‹ค์ˆ˜๋ฅผ ํ•˜๊ฑฐ๋‚˜ ์•„๋ž˜ return ๋˜๋Š” ๋ฆฌ์•กํŠธ ์ปดํฌ๋„ŒํŠธ์˜ onClick ๋ถ€๋ถ„์„ ์ž˜๋ชป ์ ์„ ๊ฒฝ์šฐ Re-Rendering์ด ๊ณ„์† ๋ฐœ์ƒํ•  ์ˆ˜ ์žˆ๋‹ค.

useTabs ํ›…์€ ๊ฐ์ฒด ํ•˜๋‚˜๋ฅผ return ํ•ด์ฃผ๊ณ , App() ํ•จ์ˆ˜ํ˜• ์ปดํฌ๋„ŒํŠธ์—์„œ๋Š” ์ด๋ฅผ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ๊ฒŒ ํ•œ๋‹ค. ๋งจ ์ฒ˜์Œ UseTabs๋Š” useState๋ฅผ ํ†ตํ•ด currentIndex๋ผ๋Š” value ํ•˜๋‚˜์™€ setCurrentIndex๋ผ๋Š” _ํ•จ์ˆ˜_๋ฅผ ๊ฐ’์œผ๋กœ ๋ฐ›๋Š”๋‹ค. ๋งŒ์ผ ์ฃผ์„ 2๋ฅผ changeItem: setCurrentIndex()๋กœ ์ž‘์„ฑํ•˜๋ฉด ํ•จ์ˆ˜๋ฅผ ๊ทธ๋Œ€๋กœ ์‹คํ–‰ํ•˜๋Š” ์…ˆ์ด์–ด์„œ ํ•จ์ˆ˜๋ฅผ ์ฐธ์กฐ๋งŒ ํ•  ๋•Œ์™€ ๋‹ฌ๋ฆฌ ํ•ญ์ƒ ์‹คํ–‰๋˜๋Š” Re-rendering ์ด์Šˆ๋ฅผ ๊ฒช๊ฒŒ ๋œ๋‹ค. ๋˜ํ•œ, <button key={index} onClick={changeItem(index)}>์ฒ˜๋Ÿผ ์ž‘์„ฑํ•ด๋„ ์•„๋ž˜์™€ ๊ฐ™์€ ์—๋Ÿฌ๋ฅผ ๋ณด๊ฒŒ ๋œ๋‹ค. ์ด๋Š” ๋งจ ์œ„ ์ฝ”๋“œ๋ฅผ onClick={() => changeItem(index)}๋กœ ๋ณ€๊ฒฝํ•˜๋ฉด ํ•ด๊ฒฐํ•  ์ˆ˜ ์žˆ๋‹ค.

Objects are not valid as a React Child

๊ฐ์ฒด ์ž์ฒด๋ฅผ ๋ Œ๋”๋งํ•ด์ฃผ๋ ค๊ณ  ํ•ด์„œ ๋‚˜์˜จ ์—๋Ÿฌ์ด๋‹ค. ๊ฐ์ฒด์˜ content๋ฅผ ํ™”๋ฉด์— ๋ณด์—ฌ์ฃผ์–ด์•ผ ํ•˜๋Š”๋ฐ ๊ฐ์ฒด๋ฅผ ๋ Œ๋”๋ง ์‹œ๋„ํ•˜๋ ค๊ณ  ํ–ˆ๊ธฐ ๋•Œ๋ฌธ์ด๋‹ค. currentItem์˜ content๋ฅผ ๋ณด์—ฌ์ฃผ๋ฉด ํ•ด๊ฒฐํ•  ์ˆ˜ ์žˆ๋‹ค.