3 글 보임 - 1 에서 3 까지 (총 3 중에서)
-
글쓴이글
-
2024년 3월 13일 10:01 #116139
변준성참가자코딩애플님 방금 로컬스토리지 수업 두개 듣고, 최근본제품이라는 페이지 만드는중인데요, Seen.js라고 파일도 만들어서 라우팅도 해놨습니다. props로 App.js에서 shoes라는 데이터 들고오고, localStorage에 있는 아이디들 긁어모아서 map함수로 화면에 뿌려주려고 하는데요, App.js에서 더보기 버튼을 누르지 않으면 4번째부터 마지막 신발 데이터는 Seen.js에서 알지 못하더라고요. 그래서 바보같지만 Seen.js 마운트되면 'https://codingapple1.github.io/shop/data2.json', 'https://codingapple1.github.io/shop/data3.json' 바로 호출해서 뿌려주려고 하는데요. 코드가 완성이 되기는 했는데, axios가 데이터를 가져오는 중간에 html이 렌더링 되니까 오류가 나더라고요. 코파일럿한테 물어봐서 코드가 작성되게 만들긴 했는데.. 데이터 부르는 함수를 useEffect안에 넣으라고 하더라고요. 근데 수업들을때는 useEffect안에 넣은 함수들은 html 다 렌더링 된 후에 실행한다고 하지 않았나요? 같은 오류를 가지고 있을거같은데 왜 이건 작동되는지 궁금합니다. 아래에 코드 올려놓을게요.
import axios from "axios"; import { useEffect, useState } from "react";
export default function Seen(props) { let 꺼낸거 = localStorage.getItem('watched'); 꺼낸거 = JSON.parse(꺼낸거); console.log(꺼낸거) const [newShoes, setNewShoes] = useState([...props.shoes]);
useEffect(() => { axios.get('https://codingapple1.github.io/shop/data2.json') .then((result)=>{ setNewShoes(prevShoes => [...prevShoes, ...result.data]); })
axios.get('https://codingapple1.github.io/shop/data3.json') .then((result)=>{ setNewShoes(prevShoes => [...prevShoes, ...result.data]); console.log(newShoes) }) }, []); // Empty dependency array means this effect runs once on mount
return ( <div> { 꺼낸거.map(function(a, i){ return ( <div key={i}> {newShoes[a]?.title} </div> ) }) } </div> ) }
2024년 3월 13일 10:05 #116141
변준성참가자부끄럽지만 제가 처음에 작성한 코드입니다.
export default function Seen(props) { axios.get("https://codingapple1.github.io/shop/data2.json").then((result) => { newShoes = [...newShoes, ...result.data]; }); axios.get("https://codingapple1.github.io/shop/data3.json").then((result) => { newShoes = [...newShoes, ...result.data]; console.log(newShoes); }); let 꺼낸거 = localStorage.getItem("watched"); 꺼낸거 = JSON.parse(꺼낸거); console.log(꺼낸거); let newShoes = [...props.shoes]; return ( <div> {꺼낸거.map(function (a, i) { return ( <div key={i}> {newShoes[a].title} {newShoes[a].content} {newShoes[a].price} </div> ); })} </div> ); }
2024년 3월 13일 14:20 #116162
codingapple키 마스터props를 state에 다시 넣어서 쓰진 않습니다 props는 부모가 준거 그대로 씁시다 html이 먼저보여져서 에러나면 state에 뭐가 들어있으면 html 보여달라고 삼항연산자 쓰면 됩니다
-
글쓴이글
3 글 보임 - 1 에서 3 까지 (총 3 중에서)
- 답변은 로그인 후 가능합니다.