3 글 보임 - 1 에서 3 까지 (총 3 중에서)
-
글쓴이글
-
2022년 11월 21일 08:58 #54865
조성백참가자현재 소스에서 App.js 는 메인페이지와 상세페이지 따로 빼주었습니다 Index.js 메인페이지에서 상품더보기를 하면 기존의 data에서 ajax에서 받은 데이터와함께 shoes에 잘 삽입이되는데요. 의문점은 메인페이지에서 상세페이지로 넘어갈땐 shoes에 들어간 데이터가 초기화되어 추가 상품더보기 전 데이터로 넘어간단 말이죠 : ( 제가 생각하기로는 계속해서 shoes 배열안에는 추가된 상품이 들어가있어야하는데 : -0 "/" 에서 "/detail/0"으로 URL이 바껴서 전부 초기화 된건지 아니면 제가 구도를 잘못잡은건지 확인해주시면 감사드리겠습니다 ㅎㅎ ''' App.js import './App.css'; import {Button, Nav, Navbar, Container, Row, Col} from 'react-bootstrap'; import { useState } from 'react'; import { Routes, Route, Link, useNavigate, Outlet } from 'react-router-dom'; import axios from 'axios';
// 화면 단 import Detail from './routes/Detail'; import Index from './routes/Index';
// Components
// Data import data from './data';
function App() { let [shoes, setShoes] = useState(data);
let navigate = useNavigate();
return ( <div className="App"> <Navbar bg="light" variant="light"> <Container> <Navbar.Brand href="/">ShoesShop</Navbar.Brand> <Nav className="me-auto"> <Nav.Link onClick={() => { navigate('/') }}>Home</Nav.Link> <Nav.Link onClick={() => { navigate('/about') }}>About</Nav.Link> <Nav.Link onClick={() => { navigate('/event') }}>Event</Nav.Link> </Nav> </Container> </Navbar>
<Routes> <Route path='/' element={<Index shoes={shoes} setShoes={setShoes}></Index>}></Route> <Route path='/detail/:id' element={<Detail shoes={shoes}></Detail>}></Route>
{/* Nested Routes : About */} <Route path='/about' element={<About></About>}> <Route path='member' element={<p>내가 제일 잘나가</p>}></Route> <Route path='location' element={<p>오디게용?!</p>}></Route> </Route> {/* Nested Routes : Event */} <Route path='/event' element={<EventPage></EventPage>}> <Route path='one' element={<p>첫 주문시 양배추즙 서비스</p>}></Route> <Route path='two' element={<p>생일 기념 쿠폰 받기</p>}></Route> </Route> <Route path='*' element={<div>그런 주소 모르는디용?</div>}></Route> </Routes> </div>); } function About(props) { return ( <div> <h1>우리 회사는요!</h1> <p>{props.shoes[0].title}</p> <Outlet shoes={props.shoes}></Outlet> </div> ); } function EventPage() { return ( <div> <h1>오늘의 이벤트</h1> <Outlet></Outlet> </div> ); } export default App; ''' ''' Index.js
import {Container, Row, Button} from 'react-bootstrap'; import axios from 'axios';
import Card from '../components/Card';
function Index(props) { const shoesList = [...props.shoes]; const shuffledArray = shoesList.sort((a, b) => 0.5 - Math.random());
const getAjax = (res) => { // const foo = shoesList.concat(res); let foo = [...shoesList, ...res];
props.setShoes(foo); };
return ( <div> <div style={ { height: "18.75rem", backgroundSize: "cover", backgroundPosition: "center", backgroundImage: `url('${process.env.PUBLIC_URL}/images/bg.png')`} }> <Button variant="success" onClick={() => {props.setShoes(shuffledArray)}} style={{"float":"right"}}>Shuffle</Button> <Button variant='warning' onClick={() => { axios.get('https://codingapple1.github.io/shop/data2.json') .then((res) => { console.log(res.data); getAjax(res.data); }) .catch((res) => { console.log(res.response.status); console.log('땡! 실패함 ㅋㅋ'); }) }} style={{"float":"right"}}>상품 더 보기</Button> </div> <Container> <Row> { props.shoes.map( (element, index) => { return (<Card key={index} index={index} shoes={element}></Card>); }) } </Row> </Container> </div> ); }
export default Index; ''' ''' Detail.js
import React, { useEffect, useState } from 'react'; import {Button, Container, Row, Col, Alert, InputGroup, Form } from 'react-bootstrap'; import { useParams } from 'react-router-dom';
function Detail(props) { let [alert, setAlert] = useState(true); let [warning, setWarning] = useState(false); let [input, setInput] = useState(""); useEffect(() => { const event = setTimeout(() => { setAlert(false); }, 2000); let cvt = Number(input); if(!isNaN(cvt)) { setWarning(true); } else { setWarning(false); }
return () => {clearTimeout(event)}; }, [input]); const { id } = useParams(); let found = props.shoes.find(function(element){ return element.id == id; }); if(found == undefined) { return (<div>그런 주소 모르는디용?</div>); } const imgUrl = "/images/shoes" + found.id + ".jpg"; return ( <div> { alert ? <Alert variant="primary">2 초 이내 클릭시 할인 쿠폰 드림.</Alert> : null } <Container> <Row> <Col>
</Col> </Row> { warning ? null : <Row><div>Warning words. please input only numbers.</div></Row> } <Row> <Col> <InputGroup> <Form.Control placeholder="Input" aria-label="Input" onChange={(e) => {setInput(e.target.value)}} /> </InputGroup> </Col> </Row> <Row> <Col> <h4>상품명 : {found.title}</h4> <p>상품설명 : {found.content}</p> <p>{found.price} 원</p> <Button variant="danger">주문하기</Button> </Col> </Row> </Container> </div> ); }
export default Detail; ''' Card.js
import {Button, Col} from 'react-bootstrap'; function Card(props) { const imgUrl = "/images/shoes" + props.shoes.id + ".jpg"; const detailUrl = "/detail/" + props.shoes.id; return ( <Col md={4}>
<h4>상품명 : {props.shoes.title}</h4> <p>상품 설명 : {props.shoes.content}</p> <p>가격 : {props.shoes.price}</p> <Button variant="outline-primary" href={detailUrl}>상세보기</Button> </Col> ); }
export default Card; '''
-
글쓴이글
3 글 보임 - 1 에서 3 까지 (총 3 중에서)
- 답변은 로그인 후 가능합니다.