Ajax?
서버에게 요청을 하는데 새로고침 없이 할 수 있게 도와주는 코드
요청에는 여러 종류가 있다.
첫번째 , GET요청
주소창에 URL 입력하는 요청
특정 페이지의 자료를 읽기!
두번째, POST 요청
정보를 숨겨서 서버에 전달하고 싶을 때 사용
읽기보단 서버로 중요 정보 전달
Ajax를 사용하는 방법은 세가지가 있다.
- JQuery 설치 후 $.ajax()
- axios 설치 후 axios.get()
- 자바스크립트 fetch()
리액트나 뷰가 많이 사용하는 라이브러리는 axios를 많이 사용한다.
설치
yarn add axios
npm install axios
import axios from 'axios’
블로그의 더보기 버튼을 구현해보자!
axios.get() 이라고 작성하면 GET요청을 새로고침 없이 데이터를 불러올 수 있다.
{
axios
.get("<https://codingapple1.github.io/shop/data2.json>")
.then((res) => {
console.log(res.data);
console.log("성공했어요");
})
.catch(() => {
console.log("실패했어요");
});
}}
>
더보기
then 안의 콜백함수 안에 파라미터를 추가하면 그게 받아온 데이터이다.
자바스크립트 문법에는 fetch로 가능하다.
우리가 가져온 데이터는 JSON이라는 데이터 자료형 인데 (따옴표가 있다.)
출력해보면 오브젝트로 나온다.
axios는 JSON을 Object로 알아서 바꿔준다.
하지만 fetch는 json 그대로 가져와서 따로 바꿔줘야한다.
그렇다면 받아온 데이터를 가지고 하단에 3개의 데이터를 추가해주자!
<내가 짠 코드>
{
axios
.get("<https://codingapple1.github.io/shop/data2.json>")
.then((res) => {
console.log(res.data);
console.log("성공했어요");
var newArray = [...sticker];
let result = res.data;
result.map((a) => {
newArray.push(a);
});
stickerChange(newArray);
console.log(sticker);
})
.catch(() => {
console.log("실패했어요");
});
}}
>
더보기
<답안>
생각도 못한 답안이 나와서 재미있었다. 😀
이런 방법으로도 문제를 풀 수 있구나,, 하면서도 리액트의 편리함에 다시한번 놀랐다, 😯
{
axios.get('<https://codingapple1.github.io/shop/data2.json>')
.then((result)=>{
stickerChange([...sticker, ...result.data ]) })
.catch(()=>{ })
}}>더보기
일단 코드를 분석하면 이렇다.
여기서 [ . . . 변수 ] 이것의 의미는 대괄호를 벗겨주세요! 라는 의미이다.
sticker의 괄호를 벗기면 {} , {} , {} 이런 형태가 될 것이고
result.data 또한 괄호를 벗기면 {} , {} , {} 이런 형태가 될 것이다.이 둘을 같은 대괄호에 넣어주면 합쳐진 배열이 완성된다!
위의 axios 경로는 똑같은 데이터밖에 없어서 같은 데이터만 나온다.
만약 더보기를 눌렀을 때 새로운 데이터를 받아오고 싶으면??
변수나 state로 누른 횟수를 저장해두고 데이터 요청을 변경하면 된다.
기능 추가하기
-더보기 버튼 클릭 시 ‘로딩 중 입니다’ 표시하기
{
//로딩중이라는 UI 띄움
axios
.get("<https://codingapple1.github.io/shop/data2.json>")
.then((res) => {
//로딩중 이라는 UI 안보이게 처리
stickerChange([...sticker, ...res.data ]) })
})
.catch(() => {
//로딩중 이라는 UI 안보이게 처리
console.log("실패했어요");
});
}}
>
더보기
이런식으로 코드를 짜면 된다.
UI를 띄우고 사라지게 하는 코드는 UI 띄움/안띄움 정보는 state에 저장해서 사용한다.
<내가 짠 코드>
/* eslint-disable*/
import "./App.css";
import {
Navbar,
Container,
Nav,
NavDropdown,
Form,
FormControl,
Button,
Spinner,
} from "react-bootstrap";
import React, { useState } from "react";
import data from "./data.js";
import { Link, Route, Switch } from "react-router-dom";
import Detail from "./Detail.js";
import axios from "axios";
function App() {
function PriceSorting() {
var newArray = [...sticker];
newArray.sort((a, b) => {
return a.price - b.price;
});
console.log(newArray);
stickerChange(newArray);
}
let [sticker, stickerChange] = useState(data);
let [loding, lodingChange] = useState(false);
return (
<div className="App">
<Navbar bg="light" expand="lg">
<Container fluid>
<Navbar.Brand href="#">Sticker shop</Navbar.Brand>
<Navbar.Toggle aria-controls="navbarScroll" />
<Navbar.Collapse id="navbarScroll">
<Nav
className="me-auto my-2 my-lg-0"
style={{ maxHeight: "100px" }}
navbarScroll
>
<Nav.Link as={Link} to="/">
Home
</Nav.Link>
<Nav.Link as={Link} to="/detail">
Detail
</Nav.Link>
<NavDropdown title="Link" id="navbarScrollingDropdown">
<NavDropdown.Item>Action</NavDropdown.Item>
<NavDropdown.Item>Another action</NavDropdown.Item>
<NavDropdown.Divider />
<NavDropdown.Item href="#action5">
Something else here
</NavDropdown.Item>
</NavDropdown>
<Nav.Link href="#" disabled>
Link
</Nav.Link>
</Nav>
<Form className="d-flex">
<FormControl
type="search"
placeholder="Search"
className="me-2"
aria-label="Search"
/>
<Button variant="outline-success">Search</Button>
</Form>
</Navbar.Collapse>
</Container>
</Navbar>
<Switch>
<Route exact path="/">
<div className="Jumbotron">
<h1>20% Season off Sale</h1>
<p>
Welcome to the sticker shop. There is a season sale, so please
check the notice. thank you.
</p>
</div>
<button className="btn" onClick={PriceSorting}>
가격정렬
</button>
<div className="container">
<div className="row">
{sticker.map((a, i) => {
return <Contents sticker={a} i={i} key={i}></Contents>;
})}
</div>
</div>
{loding === true ? (
<Spinner animation="border" role="status">
<span className="visually-hidden">Loading...</span>
</Spinner>
) : null}
<button
className="btn btn-primary"
onClick={() => {
lodingChange(true);
axios
.get("https://codingapple1.github.io/shop/data2.json")
.then((res) => {
lodingChange(false);
console.log(res.data);
console.log("성공했어요");
var newArray = [...sticker];
let result = res.data;
result.map((a) => {
newArray.push(a);
});
stickerChange(newArray);
console.log(sticker);
})
.catch(() => {
console.log("실패했어요");
});
}}
>
더보기
</button>
</Route>
<Route path="/detail/:id">
<Detail sticker={sticker} />
</Route>
<Route path="/:id">
<div>아무거나 보여주기</div>
</Route>
</Switch>
</div>
);
}
function Contents(props) {
return (
<div className="col-md-4">
<img
//src={require(`./Sketch00${props.sticker.id + 1}.jpg`)}
width="100%"
/>
<h4>{props.sticker.title}</h4>
<p>
{props.sticker.content} & {props.sticker.price}
</p>
</div>
);
}
export default App;
결과는 성공이다! 😀 재밌다 리액트
서버에 데이터를 보내고 싶을 때
-POST요청하는 법
axios.post('<https://codingapple1.github.io/shop/data2.json>', { id : 'test', pw : 1234})
.then((result)=>{ })
.catch(()=>{ })
전달하고 싶은 데이터를 넣는다. (header설정, 쿠키 전송 등 모두 가능)
-컴포넌트 로드시 ajax로 데이터를 가져올 때
Detail.js
function App(){
useEffect(()=>{
axios.get().then().catch(); //컴포넌트가 업데이트 될 때, 실행
},[]); //시작 했을 때만 가져오고 싶으면 [] 넣기 (업데이트 시 실행 x)
return (
<div>
<HTML많은곳/>
</div>
)
}
'Front-end > React' 카테고리의 다른 글
[React] 코딩애플 blog-part3-1 (Context API) (0) | 2022.01.01 |
---|---|
[React] 코딩애플 blog-part2-6 (Component 3개 만들고 props로 데이터 전송) (0) | 2021.12.31 |
[React] 코딩애플 blog-part2-4 (Lifecycle & Hook) (0) | 2021.12.28 |
[React] 코딩애플 blog-part2-3 (styled-components & SASS ) (0) | 2021.12.28 |
[React] 코딩애플 blog-part2-2 (React Router) (0) | 2021.12.27 |