import React, { useState } from 'react';
function App() {
const [todoList, setTodoList] = useState([]);
const addTodoItem = (todoList) => {
setTodoList(todoList);
// alert(todoList): XXX not updated immediately!
}
return (
<div>
<TodoForm
addTodoItem={addTodoItem}
/>
<ul>
{todoList.map(text => <li>{text}</li>)}
</ul>
</div>
)
}
function TodoForm({ addTodoItem }) {
const [todoItem, setTodoItem] = useState("Fill in your TODO item");
const handleSubmit = (event) => {
event.preventDefault();
addTodoItem(todoItem);
}
const handleTodoItemChanged = event => {
setTodoItem(event.target.value)
}
return (
<form
onSubmit={handleSubmit}
>
<input name="" type="text" value={todoItem} onChange={handleTodoItemChanged} />
<input type="submit" value="Add to the TODO list" />
</form>
)
}
export default App;
해당 댓글은 삭제되었습니다.
ㅇㅇ
아 글고 li 에 key 받아줘야돼 저런식으로 만든 컴포넌트 key로 식별키 안주면 리액트에서 못찾아서 삭제한다거나 할때 안사라진다
hook은 비동기로 함수를 실행하기 때문에 즉시 결과가 반영되지 않을 수 있음 useEffect를 활용해 todoList의 상태가 변했을 때 alert을 실행하도록 만들면 됌 useEffect(() => { if (todoList.length) { alert(todoList); } }, [todoList]);