Over the limit
버튼으로 상태 관리 하기 본문
버튼을 누를 때마다 해당 값에 알맞는 JSON 데이터를 가져와서, 원하는 자리에 채워넣고 싶음
+) 참고로 JSON 형식 지켜가면서 하기..
https://jsoneditoronline.org/#left=local.mateyi&right=local.qagaku
JSON Editor Online: JSON editor, JSON formatter, query JSON
You need to enable JavaScript to run this app. News Mobile-friendly 2022-08-29 The JSON Editor Online application is now mobile-friendly, you can enjoy it on smaller screens and touch devices too! Secure connection and open urls via proxy 2022-07-19 JSON E
jsoneditoronline.org
버튼마다 useState를 만들어서 (ex. buttonstate1, buttonstate2, ...) 관리한다? -> X
import data from './reviewItem.json'; //json 데이터 뺌
const[currentGu,setCurrentGu] = useState();
const[json,setJson] = useState();
1. '구'를 저장하는 state
2. '구'에 해당하는 'json data'를 저장하는 state
두개가 필요함!
useEffect(()=>{
setJson(data[currentGu])
console.log(json)
},[currentGu])
useEffect는 currentGu가 바뀔 때마다 실행되는 함수임. ([currentGu]말고 [] 만 넣었으면 처음 한번만 실행 된다.)
누를 때마다 데이터가 들어가고, data[currentGu]처럼 구를 특정하고,
그에 맞는 데이터가 setJson(data[currentGu])를 통해 담긴다.
data가 array형식으로, 0번째에 저장되어있는 상태이기 때문에
이 중에서 필요한 것들을 꺼내쓰면
<button>{json[0].name}</button>
다음과 같은 형식이다.
'Framework > React' 카테고리의 다른 글
[React] axios로 받은 데이터 json으로 활용하기 (0) | 2022.09.13 |
---|---|
[React] div 중앙 정렬하기, 가운데 정렬하기 (0) | 2022.09.10 |
[React] Hook : useEffect (1) | 2022.08.20 |
[React] 버튼 클릭 시 상태 변화 (0) | 2022.08.17 |
Middleware for better use of redux (0) | 2022.07.12 |