const a = [1,2,3,4];
const b = [5,6];
console.log([a, ...b])
//[[1, 2, 3, 4], 5, 6]
전개연산자는 배열 요소들이 추가되었고 그렇지 않은 것은 배열이 그대로 들어감. (객체도 가능)
결국 이런 식으로 돌아가는 것!
let copy = [...toDos];
copy.push(toDo); //or unshift
setToDos(copy);
🧨 toDos 기능구현
코드보기import { useState } from 'react';
function App() {
const [toDo, setToDo] = useState('');
const [toDos, setToDos] = useState([]);
const onChange = (e) => {
setToDo(e.target.value);
};
const onSubmit = (e) => {
e.preventDefault();
if (toDo.trim() === '') {
return alert('입력하세요');
}
setToDos((currentArray) => [toDo, ...currentArray]);
setToDo('');
};
console.log(toDos);
return (
<div>
<h1>My To Dos ({toDos.length})</h1>
<form onSubmit={onSubmit}>
<input value={toDo} onChange={onChange} type="text" placeholder="Write your to do" />
<button>Add To Do</button>
</form>
<hr />
<ul>
{toDos.map((item, index) => {
return (
<li key={index}>
{item}
<button
onClick={() => {
setToDos((current) => current.filter((value, valueIndex) => valueIndex !== index));
}}
>
X
</button>
</li>
);
})}
</ul>
</div>
);
}
export default App;
🧨 삭제기능?
<button onClick={() => {
setToDos((current) => current.filter((value) =>
toDos.indexOf(value) !== index));
}}>X</button>
//아니면 filter의 두번째 매개변수는 index기 때문에
current.filter((value,valueIndex) =>
valueIndex !== index));
또는
let copy = [...toDos];
copy.splice(index, 1);
setTodos(copy);
🧨 코인 계산기 기능구현
코드보기import { useEffect, useState } from 'react';
function App() {
const [loading, setLoading] = useState(true);
const [coins, setCoins] = useState([]);
const [index, setIndex] = useState('0');
useEffect(() => {
fetch('https://api.coinpaprika.com/v1/tickers')
.then((response) => response.json())
.then((json) => {
setCoins(json);
setLoading(false);
});
}, []);
const onSelect = (e) => {
setIndex(e.target.value);
};
return (
<div>
<h1>The Coins({coins.length})</h1>
{loading ? <strong>Loading...</strong> : null}
<select value={index} onChange={onSelect}>
{coins.map((coin, index) => {
return (
<option value={index} key={coin.id}>
{coin.name}({coin.symbol}) : {coin.quotes['USD']['price']}USD
</option>
);
})}
</select>
<UsdToCoin coins={coins} index={index} />
</div>
);
}
function UsdToCoin({ coins, index }) {
const [input, setInput] = useState(0);
const handleInput = (e) => {
setInput(e.target.value);
};
return (
<div>
<input value={input} onChange={handleInput} placeholder="your money"></input>
<input value={input !== 0 ? (input / coins[index].quotes['USD']['price']).toFixed(3) + coins[index].symbol : 0} placeholder="convert" onChange={handleInput}></input>
</div>
);
}
export default App;