Axios 2
2024. 7. 11. 18:23ㆍReact
Comments 요소들을 배열에 담아 출력하기
import React, {useState, useEffect} from 'react';
import axios from 'axios';
export default function Axios_Ex2(){
const [data, setData] = useState(null);
useEffect(() => {
axios.get("https://jsonplaceholder.typicode.com/comments")
.then(res => {
setData(res.data);
})
.catch(error => {
alert("데이터 불러오기 실패");
})
}, []);
return(
<>
<h1>json 내용 가져오기</h1>
<ul>
{data && data.map(comment =>(
<li key={comment.postId}>
<strong>PostID : </strong>{comment.postId}<br/>
<strong>ID : </strong>{comment.id}<br/>
<strong>Name : </strong>{comment.name}<br/>
<strong>Email : </strong>{comment.email}<br/>
<strong>Body : </strong>{comment.body}<br/>
</li>
))}
</ul>
{data && <textarea rows={20} cols={80} value={JSON.stringify(data, null, 2)} readOnly={true} />}
</>
)
}
.then(res => {
위의 url이 [ ]가 아니라 { }로 시작하면 { } 데이터를 감싸줄 임의의 변수명을 사용해야함.
res는 [ ]의 역할을 하며, 그 안의 "data"의 데이터를 가져옴
'React' 카테고리의 다른 글
Fetch (0) | 2024.07.12 |
---|---|
Ajax와 Fetch (0) | 2024.07.12 |
Axios 1 (0) | 2024.07.11 |
Axios, JSON (0) | 2024.07.11 |
useRef로 회원가입 폼 만들기 (0) | 2024.07.11 |