'목록 · 검색 · 더하기' 레슨의 레시피 보관함을 마무리하는 레슨입니다. 고치기 폼은 key로 고른 레시피마다 처음부터 그리고, 정렬은 toSorted로 새 배열에 담아 고른 정렬을 저장소에 남기며, 통계는 렌더할 때 목록에서 셉니다. 목록을 백업 칸에 JSON 글로 내보내고, 줄마다 모양을 검사한 뒤에만 불러옵니다.
이 단계 시작 파일은 목록 · 검색 · 더하기 레슨 예제의 파일 열하나입니다.
이 레슨은 Thinking in React 걸음 3 · 4 · 5를 혼자 밟습니다. 새로 생기는 값 다섯(고치는 레시피 · 고른 정렬 · 통계 세 수 · 보는 화면 · 백업 칸 글)이 어디에 사는지 먼저 정한 뒤 펼쳐 보세요.
값이 사는 곳 보기
| 값 | 사는 곳 |
|---|---|
고치는 레시피 editId | ListScreen state |
고른 정렬 sort | ListScreen state(useLocalStorage — 저장소에도 남음) |
| 통계 세 수 | 계산한 값 |
보는 화면 view | App state |
백업 칸 글 text · 알림 message | StatsScreen state |
고치는 레시피는 id만 둡니다. 레시피 자체는 목록에서 찾아 쓰는 계산한 값이라, 고친 뒤에도 목록과 어긋나지 않습니다.
1고치기 — key로 레시피마다 처음부터
카드마다 '고치기' 단추를 더합니다. 누르면 받은 onEdit으로 그 id를 올리고, ListScreen은 그것을 state editId(처음 null)에 둡니다. 고칠 레시피 editing은 recipes.find(…)로 찾는 계산한 값이고(JS 'map·filter·find'), editId가 null이면 찾은 것이 없어(undefined) 고치기 폼을 그리지 않습니다.
고치기 폼은 RecipeForm을 다시 씁니다. 새 props recipe의 값을 칸 셋의 처음 값으로 쓰고, 받지 않으면 기본값 blank(빈 레시피)입니다('children과 props 기본값' 레슨). 저장은 받은 레시피를 펼친 { ...recipe, … }에 칸 글만 덮어 onSave로 올립니다. id는 recipe.id ?? …라 더하기 폼에서만 새로 만들고(JS '참 같은 값과 ??'), 단추 글은 recipe.id가 있으면 '저장', 없으면 '더하기'입니다. ListScreen의 handleUpdate는 새 action updated를 보내고 setEditId(null)로 폼을 닫습니다. reducer는 id가 같은 줄만 갈아 끼웁니다(swapRecipe).
{editing && (
<RecipeForm
key={editing.id}
recipe={editing}
onSave={handleUpdate}
/>
)}useState(recipe.title)의 처음 값은 처음 렌더에만 쓰입니다. key가 없으면 폼을 연 채 다른 레시피의 '고치기'를 눌러도 같은 자리의 같은 컴포넌트라, 칸이 앞 레시피 글에 머뭅니다. key={editing.id}를 달면 레시피가 바뀔 때 폼이 처음부터 다시 섭니다('state는 자리에 산다' 레슨 4절).
2정렬 — toSorted로 새 배열에
정렬 칸(<select>)은 '더한 순'(added)과 '빠른 순'(fastest) 둘입니다. 고른 값 sort는 'useLocalStorage로 저장 빼기' 레슨의 훅 파일을 그대로 가져와 useLocalStorage로 둡니다. 키는 'recipe-box:sort', 처음 값은 'added'라, 쪽을 새로 고쳐도 고른 정렬이 남습니다.
const sorted =
sort === 'fastest'
? recipes.toSorted(byTime)
: recipes;byTime은 a.minutes - b.minutes를 돌려줘 짧은 레시피가 앞에 옵니다(JS '정렬: sort와 toSorted'). toSorted는 정렬한 새 배열을 돌려주고 목록 state는 그대로 둡니다. 보이는 목록 visible은 recipes 대신 이 sorted에서 거릅니다. 같은 자리에 recipes.sort(byTime)을 쓰면 원래 차례를 잃습니다(자주 틀리는 곳).
3통계 — 화면 둘과 렌더 중 계산
통계 화면은 새 파일 StatsScreen.jsx입니다. 목록은 ListScreen처럼 useRecipes()로 받고, 세 수는 렌더할 때마다 그 목록에서 셉니다.
const total = recipes.length;
const sum = recipes.reduce(
(s, r) => s + r.minutes,
0,
);
const average =
total === 0
? 0
: Math.round(sum / total);reduce는 분을 하나씩 더해 씨앗 넷에서 70을 냅니다(JS 'reduce로 하나로 모으기'). Math.round는 가장 가까운 정수로 반올림해, 70 ÷ 4 = 17.5가 18이 됩니다. 목록이 비면 0으로 나누지 않고 0을 씁니다. 즐겨찾기 수는 filter로 셉니다. 세 수를 state로 두면 더하기 · 지우기 · 불러오기마다 맞춰야 합니다('계산할 수 있으면 state가 아니다' 레슨).
두 화면은 App의 state view(처음 'list')로 바꿉니다. 탭 단추는 'Activity' 레슨처럼 새 파일 TabBar.jsx에 두고, 누른 단추에 따라 onTab('list')나 onTab('stats')를 부릅니다. App은 view가 'list'면 <ListScreen />을, 아니면 <StatsScreen />을 그립니다.
이 화면 바꾸기에는 한계가 있습니다. 주소가 하나라 '통계'를 눌러도 주소창이 그대로이고, 새로 고치면 view가 처음 값이라 목록 화면이 뜹니다. 뒤로 가기는 목록으로 오지 않고 이 쪽을 떠납니다. 화면마다 주소를 주는 일은 라우터(router)가 맡습니다. React Router 같은 라이브러리나 Next.js 같은 프레임워크가 그 일을 하고, 이 과목에서는 다루지 않습니다. 다음 레슨은 이 앱을 빌드해 올릴 판을 만들고, 단원 12는 할 일 화면을 TS로 옮깁니다.
4백업 — 줄마다 검사하고 불러오기
통계 화면 아래에 백업 칸(<textarea>)과 단추 둘을 둡니다. 칸 글 text와 알림 줄 message는 StatsScreen의 state이고, 칸은 'Activity' 레슨의 메모 칸처럼 value · onChange로 잇습니다. '내보내기'는 JSON.stringify(recipes)를 칸에 씁니다(JS 'JSON: 객체와 글 사이'). 그 글을 메모 앱에 옮겨 두면 백업이 됩니다.
'불러오기'는 칸 글을 readBackup으로 읽고, 검사를 다 지나야 새 action replacedAll로 목록을 갈아 끼웁니다. readBackup은 JSON.parse한 값이 배열이 아니면(Array.isArray — JS '배열과 이름 둘') '레시피 목록이 아닙니다.'를 던지고, 이어서 줄마다 봅니다.
for (const r of data) {
if (!isRecipe(r)) {
throw new Error(
'모양이 틀린 줄이 있습니다.',
);
}
}
return data;isRecipe는 한 줄이 칸 여섯을 맞는 종류로 다 갖췄는지 typeof와 Array.isArray로 봅니다 — id · title · category는 글, minutes는 수, ingredients는 배열, favorite은 참거짓. 줄이 null이어도 멈추지 않게 첫 칸은 r?.id로 꺼냅니다(JS '객체를 담은 배열'). 던진 오류는 handleImport의 catch가 받아(JS 'try와 catch') 알림 줄에 '불러오지 못했습니다: ' 뒤로 err.message를 붙입니다. JSON이 아닌 글은 JSON.parse가 먼저 던져, 크롬에서 hello는 'Unexpected token 'h', "hello" is not valid JSON'으로 알립니다.
맞혀 봅니다. readBackup에서 for 덩어리를 지워 검사가 Array.isArray 하나뿐인 판에서, 칸에 [{"title":"라면"}]을 넣고 '불러오기'를 누르면 통계 화면은 어떻게 될까요? 고른 뒤 펼쳐 보세요. 맞혀 보기는 점수에 들지 않습니다.
- ①
전체 1개·평균 NaN분 - ②
불러오지 못했습니다로 시작하는 알림 - ③ 하얀 화면
결과 보기
①입니다. 글은 JSON이고 배열이라 검사를 지나, 목록이 줄 하나로 갈아 끼워지고 저장소에도 써집니다. 알림 줄은 1개를 불러왔습니다.입니다. 그 줄에는 minutes가 없어 0 + undefined가 NaN이 되고(JS '세기: 메뉴별로 모으기'), Math.round(NaN)도 NaN입니다. 즐겨찾기는 0개입니다.
예상과 다르면 그곳이 배울 곳입니다. ②를 골랐다면 배열인지 보는 검사가 줄 안까지 본다고 생각한 것입니다. Array.isArray는 바깥이 배열인지만 봅니다. 예제 끝 판의 isRecipe도 칸의 종류까지만 봅니다 — 재료 배열 안의 값과 id가 겹치는지는 보지 않습니다. ③을 골랐다면 하얀 화면이 나는 때를 앞당겨 본 것입니다. 통계 화면은 id · ingredients를 읽지 않아 그대로 뜹니다. 하얀 화면은 '목록'을 누를 때 나고, 망가진 목록이 저장돼 새로 고쳐도 그대로입니다(해 보기 2 · 3).
예제
끝 파일 열넷입니다. 그대로인 다섯과 바뀐 다섯, 새 파일 셋은 접어 둡니다.
src/ 파일 열셋 보기 — 그대로 다섯 · 바뀐 다섯 · 새 파일 셋
코드 주석의 번호는 틀마다 셉니다 — RecipesProvider.jsx의 2.는 'reducer로 모으기', useLocalStorage.js의 2. · 3.은 '커스텀 훅으로 빼기'의 걸음이고, 나머지 3. · 4. · 5.는 Thinking in React의 걸음입니다.
src/recipes.js — 앞 레슨 그대로입니다.
export const categories = [
'한식',
'양식',
'일식',
'중식',
'디저트',
];
export const initialRecipes = [
{
id: 'r1',
title: '김치볶음밥',
category: '한식',
minutes: 15,
ingredients: [
'밥',
'김치',
'달걀',
],
favorite: true,
},
{
id: 'r2',
title: '토마토 파스타',
category: '양식',
minutes: 25,
ingredients: [
'파스타',
'토마토',
],
favorite: false,
},
{
id: 'r3',
title: '계란말이',
category: '한식',
minutes: 10,
ingredients: [
'달걀',
'파',
],
favorite: false,
},
{
id: 'r4',
title: '바나나 팬케이크',
category: '디저트',
minutes: 20,
ingredients: [
'바나나',
'밀가루',
'우유',
],
favorite: true,
},
];src/recipesContexts.js — 그대로입니다.
import {
createContext,
} from 'react';
export const RecipesContext =
createContext(null);
export const
RecipesDispatchContext =
createContext(null);src/RecipesProvider.jsx — swapRecipe와 action 갈래 둘(updated · replacedAll)을 더했습니다.
import {
useEffect,
useReducer,
} from 'react';
import {
initialRecipes,
} from './recipes.js';
import {
RecipesContext,
RecipesDispatchContext,
} from './recipesContexts.js';
const KEY =
'recipe-box:recipes';
function loadRecipes() {
const raw = localStorage
.getItem(KEY);
if (raw === null) {
return initialRecipes;
}
return JSON.parse(raw);
}
function flipFavorite(recipe) {
return {
...recipe,
favorite: !recipe.favorite,
};
}
function swapRecipe(
recipes,
next,
) {
return recipes.map((r) =>
r.id === next.id ? next : r,
);
}
// 2. action마다 새 state
function recipesReducer(
recipes,
action,
) {
switch (action.type) {
case 'added':
return [
...recipes,
action.recipe,
];
case 'updated':
return swapRecipe(
recipes,
action.recipe,
);
case 'deleted':
return recipes.filter(
(r) =>
r.id !== action.id,
);
case 'toggledFavorite':
return recipes.map(
(r) =>
r.id === action.id
? flipFavorite(r)
: r,
);
case 'replacedAll':
return action.recipes;
default:
throw new Error(
'모르는 action: ' +
action.type,
);
}
}
function RecipesProvider({
children,
}) {
const [recipes, dispatch] =
useReducer(
recipesReducer,
null,
loadRecipes,
);
useEffect(() => {
localStorage.setItem(
KEY,
JSON.stringify(recipes),
);
}, [recipes]);
return (
<RecipesContext
value={recipes}
>
<RecipesDispatchContext
value={dispatch}
>
{children}
</RecipesDispatchContext>
</RecipesContext>
);
}
export default RecipesProvider;src/useRecipes.js — 그대로입니다.
import {
useContext,
} from 'react';
import {
RecipesContext,
RecipesDispatchContext,
} from './recipesContexts.js';
export function useRecipes() {
const recipes = useContext(
RecipesContext,
);
if (recipes === null) {
throw new Error(
'useRecipes는 ' +
'RecipesProvider ' +
'안에서만 쓸 수 있습니다.',
);
}
return recipes;
}
export function
useRecipesDispatch() {
const dispatch = useContext(
RecipesDispatchContext,
);
if (dispatch === null) {
throw new Error(
'useRecipesDispatch는 ' +
'RecipesProvider ' +
'안에서만 쓸 수 있습니다.',
);
}
return dispatch;
}src/useLocalStorage.js — 새 파일입니다. 'useLocalStorage로 저장 빼기' 레슨의 파일 그대로입니다.
import {
useEffect,
useState,
} from 'react';
// 2. use로 시작하는 함수로 옮기기
function useLocalStorage(
key,
initial,
) {
function load() {
const raw = localStorage
.getItem(key);
const saved =
JSON.parse(raw);
return saved ?? initial;
}
const [value, setValue] =
useState(load);
useEffect(() => {
localStorage.setItem(
key,
JSON.stringify(value),
);
}, [key, value]);
// 3. 필요한 값만 돌려주기
return [value, setValue];
}
export default useLocalStorage;src/RecipeCard.jsx — props onEdit · 재료 줄 · '고치기' 단추를 더했습니다.
import {
useRecipesDispatch,
} from './useRecipes.js';
function RecipeCard({
recipe,
onEdit,
}) {
const dispatch =
useRecipesDispatch();
const star = recipe.favorite
? '★'
: '☆';
const items = recipe
.ingredients.join(', ');
// 5. 바꾸는 일은 위로 알리기
function handleStar() {
dispatch({
type: 'toggledFavorite',
id: recipe.id,
});
}
function handleEdit() {
onEdit(recipe.id);
}
function handleDelete() {
dispatch({
type: 'deleted',
id: recipe.id,
});
}
return (
<li>
<h3>{recipe.title}</h3>
<p>{recipe.category}</p>
<p>{recipe.minutes}분</p>
<p>{items}</p>
<button
onClick={handleStar}
>
{star}
</button>
<button
onClick={handleEdit}
>
고치기
</button>
<button
onClick={handleDelete}
>
지우기
</button>
</li>
);
}
export default RecipeCard;src/RecipeList.jsx — onEdit을 받아 카드마다 넘깁니다.
import RecipeCard from
'./RecipeCard.jsx';
function RecipeList({
recipes,
onEdit,
}) {
return (
<ul>
{recipes.map((r) => (
<RecipeCard
key={r.id}
recipe={r}
onEdit={onEdit}
/>
))}
</ul>
);
}
export default RecipeList;src/SearchBar.jsx — 그대로입니다.
function SearchBar({
query,
onQueryChange,
}) {
return (
<input
placeholder="검색"
value={query}
onChange={(e) =>
onQueryChange(
e.target.value,
)
}
/>
);
}
export default SearchBar;src/CategoryFilter.jsx — 그대로입니다.
import {
categories,
} from './recipes.js';
const choices = [
'전체',
...categories,
];
function CategoryFilter({
category,
onCategoryChange,
}) {
const buttons = choices.map(
(c) => (
<button
key={c}
className={
c === category
? 'active'
: ''
}
onClick={() =>
onCategoryChange(c)
}
>
{c}
</button>
),
);
return <div>{buttons}</div>;
}
export default CategoryFilter;src/RecipeForm.jsx — props recipe(기본값 blank)를 받아 고치기 폼으로도 씁니다.
import {
useState,
} from 'react';
import {
categories,
} from './recipes.js';
const blank = {
title: '',
category: categories[0],
minutes: '',
ingredients: [],
favorite: false,
};
function RecipeForm({
recipe = blank,
onSave,
}) {
// 4. state 자리 정하기
const [title, setTitle] =
useState(recipe.title);
const [picked, setPicked] =
useState(recipe.category);
const [minutes, setMinutes] =
useState(recipe.minutes);
function handleTitle(e) {
setTitle(e.target.value);
}
function handlePick(e) {
setPicked(e.target.value);
}
function handleMinutes(e) {
setMinutes(e.target.value);
}
// 5. 바꾸는 일은 위로 알리기
function handleSubmit(e) {
e.preventDefault();
const name = title.trim();
if (name === '') return;
onSave({
...recipe,
id:
recipe.id ??
crypto.randomUUID(),
title: name,
category: picked,
minutes: Number(minutes),
});
setTitle('');
setMinutes('');
}
const options =
categories.map((c) => (
<option key={c}>
{c}
</option>
));
const label = recipe.id
? '저장'
: '더하기';
return (
<form
onSubmit={handleSubmit}
>
<input
placeholder="이름"
value={title}
onChange={handleTitle}
/>
<select
aria-label="분류"
value={picked}
onChange={handlePick}
>
{options}
</select>
<input
type="number"
placeholder="분"
value={minutes}
onChange={handleMinutes}
/>
<button>{label}</button>
</form>
);
}
export default RecipeForm;src/ListScreen.jsx — editId · 정렬 · 고치기 폼을 더했습니다.
import {
useState,
} from 'react';
import {
useRecipes,
useRecipesDispatch,
} from './useRecipes.js';
import useLocalStorage from
'./useLocalStorage.js';
import SearchBar from
'./SearchBar.jsx';
import CategoryFilter from
'./CategoryFilter.jsx';
import RecipeList from
'./RecipeList.jsx';
import RecipeForm from
'./RecipeForm.jsx';
function byTime(a, b) {
return a.minutes - b.minutes;
}
function ListScreen() {
const recipes = useRecipes();
const dispatch =
useRecipesDispatch();
// 4. state 자리 정하기
const [query, setQuery] =
useState('');
const [picked, setPicked] =
useState('전체');
const [editId, setEditId] =
useState(null);
const [sort, setSort] =
useLocalStorage(
'recipe-box:sort',
'added',
);
// 3. 가장 작은 state 찾기
const sorted =
sort === 'fastest'
? recipes.toSorted(byTime)
: recipes;
const visible = sorted
.filter(
(r) =>
r.title.includes(query),
)
.filter(
(r) =>
picked === '전체' ||
r.category === picked,
);
const favoriteCount =
recipes.filter(
(r) => r.favorite,
).length;
const editing = recipes.find(
(r) => r.id === editId,
);
// 5. 바꾸는 일은 위로 알리기
function handleSave(recipe) {
dispatch({
type: 'added',
recipe,
});
}
function handleUpdate(next) {
dispatch({
type: 'updated',
recipe: next,
});
setEditId(null);
}
function handleSort(e) {
setSort(e.target.value);
}
return (
<section>
<SearchBar
query={query}
onQueryChange={setQuery}
/>
<CategoryFilter
category={picked}
onCategoryChange={
setPicked
}
/>
<select
aria-label="정렬"
value={sort}
onChange={handleSort}
>
<option value="added">
더한 순
</option>
<option value="fastest">
빠른 순
</option>
</select>
<p>
즐겨찾기 {favoriteCount}개
</p>
<RecipeList
recipes={visible}
onEdit={setEditId}
/>
{editing && (
<RecipeForm
key={editing.id}
recipe={editing}
onSave={handleUpdate}
/>
)}
<RecipeForm
onSave={handleSave}
/>
</section>
);
}
export default ListScreen;src/TabBar.jsx — 새 파일입니다.
function TabBar({ onTab }) {
function toList() {
onTab('list');
}
function toStats() {
onTab('stats');
}
return (
<nav>
<button onClick={toList}>
목록
</button>
<button onClick={toStats}>
통계
</button>
</nav>
);
}
export default TabBar;src/StatsScreen.jsx — 새 파일입니다.
import {
useState,
} from 'react';
import {
useRecipes,
useRecipesDispatch,
} from './useRecipes.js';
function isRecipe(r) {
return (
typeof r?.id === 'string' &&
typeof r.title ===
'string' &&
typeof r.category ===
'string' &&
typeof r.minutes ===
'number' &&
Array.isArray(
r.ingredients,
) &&
typeof r.favorite ===
'boolean'
);
}
function readBackup(text) {
const data = JSON.parse(text);
if (!Array.isArray(data)) {
throw new Error(
'레시피 목록이 아닙니다.',
);
}
for (const r of data) {
if (!isRecipe(r)) {
throw new Error(
'모양이 틀린 줄이 있습니다.',
);
}
}
return data;
}
function StatsScreen() {
const recipes = useRecipes();
const dispatch =
useRecipesDispatch();
// 4. state 자리 정하기
const [text, setText] =
useState('');
const [message, setMessage] =
useState('');
// 3. 가장 작은 state 찾기
const total = recipes.length;
const sum = recipes.reduce(
(s, r) => s + r.minutes,
0,
);
const average =
total === 0
? 0
: Math.round(sum / total);
const favoriteCount =
recipes.filter(
(r) => r.favorite,
).length;
// 5. 바꾸는 일은 위로 알리기
function handleText(e) {
setText(e.target.value);
}
function handleExport() {
const json =
JSON.stringify(recipes);
setText(json);
setMessage('');
}
function handleImport() {
try {
const data =
readBackup(text);
dispatch({
type: 'replacedAll',
recipes: data,
});
setMessage(
data.length +
'개를 불러왔습니다.',
);
} catch (err) {
setMessage(
'불러오지 못했습니다: ' +
err.message,
);
}
}
return (
<section>
<p>전체 {total}개</p>
<p>평균 {average}분</p>
<p>
즐겨찾기 {favoriteCount}개
</p>
<textarea
aria-label="백업"
value={text}
onChange={handleText}
/>
<button
onClick={handleExport}
>
내보내기
</button>
<button
onClick={handleImport}
>
불러오기
</button>
<p>{message}</p>
</section>
);
}
export default StatsScreen;src/App.jsx는 세 조각이고, 셋 다 바뀌었습니다. 첫 조각은 가져오기입니다.
import {
useState,
} from 'react';
import RecipesProvider from
'./RecipesProvider.jsx';
import TabBar from
'./TabBar.jsx';
import ListScreen from
'./ListScreen.jsx';
import StatsScreen from
'./StatsScreen.jsx';App은 view로 그릴 화면을 고릅니다. 앞 코드에 이어 씁니다.
function App() {
const [view, setView] =
useState('list');
const screen =
view === 'list' ? (
<ListScreen />
) : (
<StatsScreen />
);코드 아래 화면은 저장소가 씨앗 넷일 때(키를 지우는 길은 해 보기 3) 김치볶음밥의 '고치기'에서 분을 5로 바꿔 저장하고, '통계'에서 백업 칸에 [{"title":"라면"}]을 넣어 '불러오기'를 누른 뒤 화면입니다. 찍어 둔 화면이라 눌러도 바뀌지 않습니다. 앞 코드에 이어 씁니다.
return (
<RecipesProvider>
<main>
<h1>레시피 보관함</h1>
<TabBar
onTab={setView}
/>
{screen}
</main>
</RecipesProvider>
);
}
export default App;<main><h1>레시피 보관함</h1><nav><button>목록</button><button>통계</button></nav><section><p>전체 4개</p><p>평균 15분</p><p>즐겨찾기 2개</p><textarea aria-label="백업">[{"title":"라면"}]</textarea><button>내보내기</button><button>불러오기</button><p>불러오지 못했습니다: 모양이 틀린 줄이 있습니다.</p></section></main>5분으로 고친 김치볶음밥이 들어가 평균은 15분이고, 모양이 틀린 줄은 알림만 남긴 채 목록은 그대로입니다. 콘솔에 빨간 줄은 없습니다.
src/App.jsx 전체 보기
import {
useState,
} from 'react';
import RecipesProvider from
'./RecipesProvider.jsx';
import TabBar from
'./TabBar.jsx';
import ListScreen from
'./ListScreen.jsx';
import StatsScreen from
'./StatsScreen.jsx';
function App() {
const [view, setView] =
useState('list');
const screen =
view === 'list' ? (
<ListScreen />
) : (
<StatsScreen />
);
return (
<RecipesProvider>
<main>
<h1>레시피 보관함</h1>
<TabBar
onTab={setView}
/>
{screen}
</main>
</RecipesProvider>
);
}
export default App;다음 레슨이 이 파일 열넷에서 이어 갑니다.
자주 틀리는 곳
틀린 생각: 정렬은 recipes.sort(byTime)으로 해도 같다.
? recipes.sort(byTime)'빠른 순'은 같아 보입니다. 그런데 sort는 목록 state 배열을 제자리에서 바꿔, '더한 순'으로 돌아와도 계란말이가 맨 앞에 남습니다. 콘솔은 조용합니다.
맞는 규칙: state 배열은 고치지 않고 새 배열을 만듭니다('배열 state' 레슨). 정렬은 새 배열을 돌려주는 toSorted로 합니다(JS '정렬: sort와 toSorted').
틀린 생각: 통계 화면에 갔다 와도 검색 칸 글은 남는다.
검색 칸에 밥을 치고 '통계'에 갔다가 '목록'으로 돌아오면 검색 칸이 비고 모두 보입니다. 통계 화면을 그리는 동안 ListScreen이 빠져 그 state가 사라지고, 돌아오면 처음 값 ''부터 다시 섭니다.
맞는 규칙: 자리에서 빠진 컴포넌트의 state는 남지 않습니다. 지키려면 'Activity' 레슨처럼 <Activity>로 감싸 숨기거나, 검색 글을 App으로 올립니다.
확인 문제
1. 예제 끝 판(씨앗 넷)에서 고치기 폼의 key={editing.id} 줄을 지웠습니다. 김치볶음밥의 '고치기'를 누르고, 폼을 연 채 토마토 파스타의 '고치기'를 누른 뒤 '저장'을 누릅니다. 저장 직전의 폼 칸과 저장 뒤의 카드는 어떻게 될까요?
- ① 칸
토마토 파스타· 카드 넷 그대로 - ② 칸
김치볶음밥· 카드 넷 그대로 - ③ 칸
김치볶음밥·김치볶음밥카드 두 장
정답
③입니다. key가 없으면 폼 자리의 컴포넌트가 그대로라 칸 state는 처음 렌더 값 김치볶음밥 · 한식 · 15에 머뭅니다. 그런데 props recipe는 토마토 파스타라, 저장은 { ...recipe, … }에 id 'r2'를 싣고 칸 글을 덮어 올립니다. swapRecipe가 r2 자리를 갈아 끼워 김치볶음밥이 두 장이 되고, 콘솔은 조용합니다.
- ① props가 바뀌면 칸 state도 따라 바뀐다고 본 것입니다.
useState의 처음 값은 처음 렌더에만 쓰입니다(1절). - ② 저장이 칸에 보이는 레시피를 고친다고 본 것입니다. 갈아 끼울 줄은 props
recipe의id로 찾습니다.
2. 예제 끝 판에서 정렬 칸을 '빠른 순'으로 고르고, 김치볶음밥의 '고치기'를 눌러 폼을 연 채 '통계'를 누릅니다. 다시 '목록'을 누르면 어떻게 될까요?
- ① 빠른 순 그대로이고, 고치기 폼도 열려 있다
- ② 빠른 순 그대로이고, 고치기 폼은 닫혀 있다
- ③ 더한 순으로 돌아오고, 고치기 폼은 닫혀 있다
정답
②입니다. 통계 화면을 그리는 동안 ListScreen이 빠져 state editId가 사라지고, 돌아오면 처음 값 null부터라 고치기 폼이 없습니다. 정렬도 ListScreen 안의 훅이지만, 처음 값을 저장소 recipe-box:sort에서 꺼내 'fastest'로 다시 섭니다.
- ① 화면을 바꿔도
ListScreen이 남는다고 본 것입니다.App은view에 따라 둘 가운데 하나만 그립니다. - ③ 정렬도
useState처럼 처음 값으로 돌아간다고 본 것입니다.useLocalStorage는 처음 값을 저장소에서 읽습니다(2절).
3. 예제 끝 판의 통계 화면에서 백업 칸에 []를 넣고 '불러오기'를 누릅니다. 통계 화면은 어떻게 될까요?
- ①
전체 0개·평균 0분·즐겨찾기 0개 - ②
불러오지 못했습니다로 시작하는 알림, 통계는 그대로 - ③
전체 0개·평균 NaN분·즐겨찾기 0개
정답
①입니다. []는 JSON이고 배열이라 첫 검사를 지나고, 줄이 없어 for는 한 번도 돌지 않습니다. replacedAll로 목록이 비고 알림 줄은 0개를 불러왔습니다.입니다. total이 0이라 평균은 나누지 않고 0입니다.
- ② 빈 목록은 검사가 막는다고 본 것입니다. 검사는 배열인지와 줄마다의 모양만 봅니다 — 걸릴 줄이 없습니다.
- ③ 0으로 나눈다고 본 것입니다.
total === 0이면Math.round(sum / total)을 부르지 않습니다(3절).
컴퓨터에서 해 보기(선택) — 점수에 들지 않습니다. 폰으로만 보고 있다면 건너뛰세요.
- 예제 끝 판으로 고치기 · 정렬 · 통계를 해 보고 쪽을 새로 고칩니다. 고친 레시피와 고른 정렬은 남고, 화면은 목록으로 돌아옵니다. 개발 도구의 Application 판에서 Storage 아래
Local Storage를 펼치고, 개발 서버 주소를 골라 키recipe-box:recipes와recipe-box:sort를 봅니다. - 통계 화면의 '내보내기'를 눌러 칸 글을 메모 앱에 옮겨 둡니다.
src/StatsScreen.jsx도 메모 앱에 옮겨 두고,readBackup의for덩어리 일곱 줄을 지워 저장합니다. 칸에[{"title":"라면"}]을 넣고 '불러오기'를 누르면 맞혀 보기 답대로전체 1개·평균 NaN분입니다. - '목록'을 누릅니다. 화면이 하얗게 비고, 콘솔에 빨간 줄 'Each child in a list should have a unique "key" prop.'과
Uncaught TypeError:로 시작하는 빨간 줄 'Cannot read properties of undefined (reading 'join')', 'An error occurred in the<RecipeCard>component.'로 시작하는 노란 줄이 차례로 찍힙니다. 망가진 목록이 저장돼 쪽을 새로 고쳐도 그대로입니다. Application 판에서recipe-box:recipes줄을 골라 위쪽 도구 줄의 Delete로 지우고 새로 고치면 씨앗 넷이 돌아옵니다.src/StatsScreen.jsx를 메모 앱 판으로 되돌리고, 내보내 둔 글을 칸에 넣어 '불러오기'를 누르면 고친 목록도 돌아옵니다.