這次來做上次未做完的"新增",後續還要做"修改"、"刪除",並儲存至資料庫
function ToDoList() {
const [datas, setDatas] = useState([]);
useEffect(() => {
fetch('/api/todolists')
.then(response => response.json())
.then(json => setDatas(json))
.catch(error => console.error(error));
}, []);
return (
<>
<h1>代辦事項</h1>
<ToDoListCreate />
{
datas.map((data) => (
<ToDoListItem
key={data.id}
Name={data.name}
Checked={data.checked == null ? false : data.checked}
onDelete={() => {
setDatas(datas.filter((a) => a.Key !== data.Key))
}}
></ToDoListItem>
))
}
</>
);
}
export default ToDoList;
function ToDoListCreate() {
return (
<>
<Button variant="primary">新增</Button>{' '}
</>
)
}
<ToDoListCreate
onCreate={() => {
setDatas(pre => [...pre, {}]);
console.log(datas);
}}
></ToDoListCreate>
function ToDoListCreate(prop) {
return (
<>
<Button variant="primary" onClick={prop.onCreate}>新增</Button>{' '}
</>
)
}