์ถ์ฒ: React doc
{isPlayerA ? (
<Counter person="Taylor" />
) : (
<Counter person="Sarah" />
)}
{isPlayerA &&
<Counter person="Taylor" />
}
{!isPlayerA &&
<Counter person="Sarah" />
}
๐ ์ฝ๋ 1์ ๊ฒฝ์ฐ ๊ฐ์ Counter๋ก ์ธ์ํจ. ์ฝ๋ 2์ ๊ฒฝ์ฐ ๋ค๋ฅธ Counter๋ก ์ธ์ํ์ฌ state ๊ณต์ ๋ฅผ ํ์ง ์์.
This solution is convenient when you only have a few independent components rendered in the same place.
๐ ๋๊ฐ์ ๊ฐ์ component๊ฐ ์์ ๊ฒฝ์ฐ ์ ์ฉํ ๋ฐฉ๋ฒ.
{isPlayerA ? (
<Counter key="Taylor" person="Taylor" />
) : (
<Counter key="Sarah" person="Sarah" />
)}
You might have seen keys when rendering lists. Keys arenโt just for lists! You can use keys to make React distinguish between any components. By default, React uses order within the parent (โfirst counterโ, โsecond counterโ) to discern between components. But keys let you tell React that this is not just a first counter, or a second counter, but a specific counterโfor example, Taylorโs counter. This way, React will know Taylorโs counter wherever it appears in the tree!
This is why, even though you render them in the same place in JSX, React sees them as two different counters, and so they will never share state. Every time a counter appears on the screen, its state is created. Every time it is removed, its state is destroyed.
๐ component์ ์ด๋ฆ์ด ๊ฐ์๋ key๋ฅผ ๋ถ์ด๋ ์๊ฐ ๊ฐ๊ฐ ๋ค๋ฅธ component๋ก ์ธ์ํ๋ค. ๋ค๋ฅธ componet๋ก ์ธ์๋๊ธฐ ๋๋ฌธ์ state๋ฅผ ์ ๋๋ก ๊ณต์ ํ์ง ์๋๋ค.
Note
Remember that keys are not globally unique. They only specify the position within the parent.