ReactJS

react기초 - 노마더코더 ( 영화 웹 서비스 만들기 )

PHM 2022. 3. 11. 11:52

화살표 함수

function a(){
	return();
}

// 두 개의 의미는 같다!
const b = () => (

);

 

- react는 UI에서 바뀐부분만 업데이트 해줌 

  기존의 바닐라같은 경우는 해당태크 및 body태그가 함께 업데이트됨.

- State : 기본적으로 데이터가 저장되는 곳

- React.useState

let a = 0;
function ab() {
}

// 같음
const [a,ab] = React.useState(0);	// 배열로 [0,f] 로 들어가있음

- 데이터가 바뀔때마다 컴포넌트를 리렌더링하고 UI를 refresh한다.

 

- state 변경방식

  1. 직접 할당 : setState(state+1) 

     - 현재 state랑 관련이 없는 값을 새로운 state로 하고 싶은 경우

  2. 함수 할당 : setState(state => state+1) ( 함수의 첫번쨰 인자는 현재 state이다 )

     - 현재 state에 조금의 변화를 주어서 새로운 state를 주고 싶은 경우

 

- html

  label : input옆에 써주는 글씨 / 클릭시 input 선택 / for속성을 input의 id값과 같게해서 연결

- js와 jsx

  js :  class , for

  jsx : className, htmlFor

  

 

- onChange : 데이터를 업데이트 / 이벤트를 리스닝

const [minutes, setMinutes] = React.useState();
const onChange = (event) => {
	setMinutes(event.target.value);
}

<input
	value={minutes}
	onChange = {onChange}
></input>

 

- input의 disabled 속성 : 쓰기 불가능 속성

  상태변경코드 enable <-> disabled

const [amount, setAmount] = React.useState(0);
const [flipped, setFlipped] = React.useState(false);
cont onFlip = () => {
	reset();	// () => setAmount(0);
	setFlipped((current) => !current);
};

<input
	value={flipped ? amount*60 : amount}
	disabled = {flipped === true}
></input>

<input
	value={flipped ? amount : Math.round(amount/60)}
	disabled = {flipped === false}
></input>

<button onClick={onFlip}>flip{flipped? "Turn back" : "Invert"}</button>

 

- select 태그 활용

const [index, setIndex] = React.useState(0);
const onSelect = (event) => {
	setIndex(event.target.value);
};

return(
	<select value={index} onChange={onSelect}>
		<option value="0"></option>
		<option value="1"></option>
        {index === "0" ? <MinutesToHours /> : null}
        {index === "1" ? <KmToMiles /> : null}
	</select>
}

 

- component : jsx를 반환하는 함수

 

- props

  함수형컴포넌트에서 매개인자로 받으면 된다. ->  function a(props) {}

  props는 오브젝트

  함수도 보낼 수 있음 -> 하지만 하위컴포넌트 오브젝트로 받아서 실행시켜줘야함

 

- shortcut

   property를 오브젝트로부터 꺼냄

// 1.props
function(props){
	{props.banna}
}
// 2.shortcut
function({banna}){
	{banna}
}

 

- PropType : 어떤 타입의 prop을 받고 있는지를 체크

import ProTypes from "prop-types";

Btn.propTypes = {
	text: PropTypes.string,
    fontSize:PropTypes.number.isRequired
}

  .isRequired : 필수 props속성

// 설치
npm i prop-types

 

- module.css

  create-react-app은 css코드를 javascript 오브젝트로 변환가능

import styles from "./Button.module.css";

<button className={styles.btn}></button>

실행하면 무작위적인 랜덤 class를 갖는다.

style들도 modular(모듈러)가 될 수 있다!

다른 클래스 이름들을 사용하기 위해 기억하고 있어야만 하는 것보다 좋음 / 즉 같은 클래스을 붙여도 다른 css적용가능

 

- form

<form 
	onSubmit = { (event) => {
		event.preventDefault();
        if(toDo === ""){
			return ;
		}
        setToDo("");
	}
></form>

 

- array state

const [toDos, setToDos] = useState([]);

setToDos(currentArray => [toDo, ...currentArray])

// ...array : 배열자체를 저장하지않고 배열의 요소들만 넣어준다.

 

- map : 내가 return한 어떠한 값은 새로운 array에 들어감 

  리스트 출력시 사용

['there','are'].map(()=>":)")

// 2개의 :) 출력

map은 함수의 첫번째 argument로 현재의 item을 가져올 수 있다.

<ul>
	{toDos.map((item, index) => (
		<li key={index}>{itme}</li>
))}
</ul>

 

- fetch(url) : url로부터 response를 받아옴

useEffect(() => {
	fetch(url).then(response => 
		response.json();
	).then(json => console.log(json));
},[]);

 

- then 대신 async-await 사용

const getMoives = async() => {
	const response = await fetch(url);
	const json = await response.json();
    setMoives(json.data.movies);
};

const getMoives = async() => {
	const json = await(
		await fetch(url)
	).json();
}

-route

 Hash Router : url에 #이 붙음

 Browser Router : 우리가 일반적으로 생각하는 url

 

Switch : Route(url) 를 찾음. 한번에 하나의 Route만 랜더링하기 위해서

<Router>
	<Switch>
		<Route path="/">
			<Home />
 		</Route>
	</Switch>
</Router>

Link : 브라우저 새로고침 없어도 유저를 다른 페이지로 이동시켜주는 컴포넌트

 

- 동적 url 방식 ( get방식 )

// 1. 전송 방식
<Route path="/movie/:id">

<Link to={`/movie/${id}`}>

// 2. 사용 방식
const {id} = useParams();