• 로그인
  • 장바구니에 상품이 없습니다.

home2 게시판 React 게시판 Context API

Context API

3 글 보임 - 1 에서 3 까지 (총 3 중에서)
  • 글쓴이
  • #29930

    현정
    참가자

    part3 context api 강의랑 똑같이 하니까 react app이 아무것도 안보이는데 왜이러는건가요..?

    변경한건

    let 재고context = React.createContext();

    <재고context.Provider value={재고}>
          {/* 같은값을 공유할 html을 <범위>로 싸매기 */}
            <div className="row">
               {
                 shoes.map((a, i)=>{
                   return <Card shoes={shoes[i]} i={i} key={i} />

                 })
               }
            </div>
            </재고context.Provider>

    function Card(props){
      let 재고 = useContext(재고context);
      return (
        <div className="col-md-4">
         
          <h4>{ props.shoes.title }</h4>
          <p>{ props.shoes.content } & { props.shoes.price }</p>
          <Text></Text>
        </div>
      )
    }

    function Test(){
      let 재고 = useContext(재고context)
      // 3.useContext로 공유된 값사용하기
      return <p>{재고}</p>
    }

    이부분밖에 없는데

    /*eslint-disable*/
    /* eslint no-restricted-globals: ["off"] */
    // 위에꺼 history 적용을 위해 씀
    import React, {useContext, useState} from 'react';
    import logo from './logo.svg';
    import './App.css';
    import { Navbar,Container,Nav,NavDropdown,Jumbotron} from 'react-bootstrap';
    import Data from './data.js';
    import Detail from './Detail.js'
    import {Link, Route, Switch } from 'react-router-dom';
    import axios from 'axios';

    let 재고context = React.createContext();
    // 1.같은 변수값을 공유할 범위를 생성해주는 문법
    function App() {

      let [shoes,shoes변경] = useState(Data)
      let [클릭횟수,클릭횟수변경] = useState(2)
      let [재고,재고변경] = useState([10,11,12])
      return (
        <div className="App">
          <nav class="navbar navbar-expand-lg navbar-light bg-light">
      <div class="container-fluid">
        <a class="navbar-brand" href="#">Navbar</a>
        <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
          <span class="navbar-toggler-icon"></span>
        </button>
        <div class="collapse navbar-collapse" id="navbarSupportedContent">
          <ul class="navbar-nav me-auto mb-2 mb-lg-0">
            <li class="nav-item">
              <a class="nav-link active" aria-current="page" href="#"> <Link to="/">HOME</Link></a>
            </li>
            <li class="nav-item">
              <a class="nav-link" href="#"><Link to="/detail">Detail</Link></a>
            </li>
            <li class="nav-item dropdown">
              <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-bs-toggle="dropdown" aria-expanded="false">
                Dropdown
              </a>
              <ul class="dropdown-menu" aria-labelledby="navbarDropdown">
                <li><a class="dropdown-item" href="#">Action</a></li>
                <li><a class="dropdown-item" href="#">Another action</a></li>
                <li><hr class="dropdown-divider"/></li>
                <li><a class="dropdown-item" href="#">Something else here</a></li>
              </ul>
            </li>
            <li class="nav-item">
              <a class="nav-link disabled">Disabled</a>
            </li>
          </ul>
          <form class="d-flex">
            <input class="form-control me-2" type="search" placeholder="Search" aria-label="Search"/>
            <button class="btn btn-outline-success" type="submit">Search</button>
          </form>
        </div>
        </div>
        </nav>
       
       <Switch>
          <Route exact path="/">
          <div class="jumbotron background">
            <h1 class="display-4">Hello, world!</h1>
            <p class="lead">This is a simple hero unit, a simple jumbotron-style component for calling extra attention to featured content or information.</p>
            <hr class="my-4"/>
            <p>It uses utility classes for typography and spacing to space content out within the larger container.</p>
            <a class="btn btn-primary btn-lg" href="#" role="button">Learn more</a>
          </div>
       
          <div className="container">
          <재고context.Provider value={재고}>
          {/* 같은값을 공유할 html을 <범위>로 싸매기 */}
            <div className="row">
               {
                 shoes.map((a, i)=>{
                   return <Card shoes={shoes[i]} i={i} key={i} />

                 })
               }
            </div>
            </재고context.Provider>
            <button className='btn btn-primary' onClick={()=> {
              // 로딩중이라는 UI띄움
           
              axios.get("https://codingapple1.github.io/shop/data"+클릭횟수+".json")
              .then( (result)=> {
                클릭횟수변경(클릭횟수+1)
                // 로딩중이라는 UI안보이게 처리  
                shoes변경( [...shoes, ...result.data] )
                // 데이터가져와서 shoes라는 state에 추가
               })
              // 성공했을때
              .catch( ()=> {
                console.log('실패했어요')
              })
              // 실패했을때
            }}>더보기</button>
          </div>
          </Route>
         
         
          <Route path="/detail/:id">
            < Detail shoes={shoes} 재고={재고} 재고변경={재고변경}/>
          </Route>

          <Route path="/:id">
            {/* 아무주소 다 적어도 적용되는거 */}
          </Route>
          </Switch>  
          {/* switch:중복사용안되게해줌 */}
        </div>

       
      );
    }

    function Card(props){
      let 재고 = useContext(재고context);
      return (
        <div className="col-md-4">
         
          <h4>{ props.shoes.title }</h4>
          <p>{ props.shoes.content } & { props.shoes.price }</p>
          <Text></Text>
        </div>
      )
    }

    function Test(){
      let 재고 = useContext(재고context)
      // 3.useContext로 공유된 값사용하기
      return <p>{재고}</p>
    }

    export default App;

    #29931

    현정
    참가자

    제가 오타난게 있었네요 저는 멍청이입니다 멍청이는 다시 수정하러 가볼게요,,

    detail.js에서 쓸려면 import,export 한다음에 app.js에서 한것처럼 똑같이 하면되나용?

    #29945

    codingapple
    키 마스터

    네 근데 최상위 컴포넌트만 <어쩌구Provider> 로 묶어놓으면 모든 컴포넌트가 쓸 수 있을듯요 

3 글 보임 - 1 에서 3 까지 (총 3 중에서)
  • 답변은 로그인 후 가능합니다.

About

현재 월 700명 신규수강중입니다.

  (09:00~20:00) 빠른 상담은 카톡 플러스친구 코딩애플 (링크)
  admin@codingapple.com
  이용약관, 개인정보처리방침
ⓒ Codingapple, 강의 예제, 영상 복제 금지
top

© Codingapple, All rights reserved. 슈퍼로켓 에듀케이션 / 서울특별시 강동구 고덕로 19길 30 / 사업자등록번호 : 212-26-14752 온라인 교육학원업 / 통신판매업신고번호 : 제 2017-서울강동-0002 호 / 개인정보관리자 : 박종흠