react.js 기본 (노마드 강의) - 실습 - todolist, coin 환전 해보기

mini·2022년 11월 18일
0

state 연습

  • set 함수(수정하는 함수)
    - setData("") : 기본값 값만 보내기
    • setData(func(argument)) : 첫번째 argument에 함수를 쓰면 현재 State로 보낸다. 이 현재 State를 이용해서 새로운 지금 State를 계산할 수 있게 된다.

map() 함수

  • ['hi','hello','yep'].map((item) => func)
    - 각 배열에 위치한 값을 조작한다.
    - map() 여기에 적은 함수가 각각의 배열 마다 함수를 하나씩 실행된다.
    - 그 함수로 부터 내가 return 한 어떤 값은 새로운 array 에 들어간다.
    - 첫번째 argument는 지금 item을 가져올수 잇다 두번째는 해당 배열의 index값을 알수있다.

같은 컴포넌트의 list를 render 할 때 key라는 prop을 넣어야 한다.

react_devtools_backend.js:4026 Warning: Each child in a list should have a unique "key" prop.

기본적으로 react 는 list 있는 모든 item들을 인식 하기 때문이다.
키는 고유의 값이여아 한다.

코인 api 받고 해당 코인 셀렉트 박스로 나타내고 셀렉된 코인 환전 하기 연습문제

import { useState, useEffect } from "react";

function App() {
  const [loading, setLoading] = useState(true);
  const [coins, setCoins] = useState([]); 
  //useState() 빈값으로 두면 api 블러 오기전에 아래에 coin.length 나 coin.name이 undefined 이기 때문에 에러가 난다 useState([]) 기본값을 정해주면 적어도 undefind는 아니기 때문에 에러가 안난다.(기본값을 항상 정해둬야 udnefined가 나지 않는다.)

  useEffect(() => {
    fetch("https://api.coinpaprika.com/v1/tickers")
      .then((response) => response.json())
      .then((json) => {
        setCoins(json);
        setLoading(false);
      });
  }, []);

  const [buyCoins, setBuyCoins] = useState(0);
  const onChange = (event) => {
    setBuyCoins(event.target.value);
  };

  const [exchangeCoins, setExchangeCoins] = useState(0);
  const [coinSybol, setCoinSybol] = useState("");

  //when choose coin slelect caculate excahnge coin and show sybol
  const selectChange = (event) => {
    const result = buyCoins / event.target.value;
    setExchangeCoins(result);

    const targetCoinSybol =
      event.target[event.target.selectedIndex].attributes.name.value;
    setCoinSybol(targetCoinSybol);
  };

  return (
    <div>
      <h1>The Coins{loading ? "" : `(${coins.length})`}</h1>
      {loading ? (
        <strong>Loading...</strong>
      ) : (
        <select onChange={selectChange}>
          {coins.map((coin) => (
            <option
              key={coin.id}
              value={coin.quotes.USD.price}
              name={coin.symbol}
            >
              {coin.name}({coin.symbol}) : $ {coin.quotes.USD.price}
            </option>
          ))}
        </select>
      )}
      <br />
      $
      <input onChange={onChange} value={buyCoins} />
      환전 된 돈:
      <input value={exchangeCoins} readOnly />
      <span style={{ color: "red" }}>{coinSybol}</span>
      <button>구매하기</button>
    </div>
  );
}

export default App;

0개의 댓글