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

home2 게시판 React 게시판 React Router 2 : Link, Switch, history 기능 강의 관련 질문입니다.

React Router 2 : Link, Switch, history 기능 강의 관련 질문입니다.

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

    김관영
    참가자

    Detail.js 에서 useHistory 사용 시, Hook 관련 에러가 납니다.

    에러 내용은 아래와 같습니다.

    Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons: 1. You might have mismatching versions of React and the renderer (such as React DOM) 2. You might be breaking the Rules of Hooks 3. You might have more than one copy of React in the same app See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.

     

    현제 저의 소스 입니다.

    import React, { useState } from 'react';
    import { useHistory } from 'react-router-dom';

    function Detail() {
      
      let history = useHistory();
      
      return (
        <div className="container">
          <div className="row">
            <div className="col-md-6">
              <img src="https://codingapple1.github.io/shop/shoes1.jpg" width="100%" />
            </div>
            <div className="col-md-6 mt-4">
              <h4 className="pt-5">상품명</h4>
              <p>상품설명</p>
              <p>120000원</p>
              <button className="btn btn-danger">주문하기</button>
              <button className="btn btn-danger" onClick={() => { history.goBack() }}>뒤로가기</button>
            </div>
          </div>
        </div>
      )
    }

    export default Detail;

     

    1.  App.js에서는 동일하게 history 변수 생성 시 문제 없음.

    2. Detail.js에서는 useHistory뿐만 아니라  useState도 변수 생성 시 같은 에러 발생.

    -> App.js가 아닌 다른 파일에서 Hook 관련 내용 사용 시 에러가 나는 것 같습니다.

     

    해결방법이 있을까요?

    감사합니다.

    #8436

    codingapple
    키 마스터

    app.js에서의 라우팅이나 index.js셋팅같은거 잘 되어있나요?

    #8447

    김관영
    참가자

    답변 감사합니다.

     

    app.js 소스

    function App() {

      let [shoes, changeShoes] = useState(Data);

      return (
        <div className="App">
          <Navbar bg="light" expand="lg" className="">
              <Navbar.Brand href="#home">ShoeShop</Navbar.Brand>
              <Navbar.Toggle aria-controls="basic-navbar-nav" />
              <Navbar.Collapse id="basic-navbar-nav">
                <Nav className="mr-auto">
                  <Nav.Link><Link to="/">Home</Link></Nav.Link>
                  <Nav.Link><Link to="/detail">Detail</Link></Nav.Link>
                  <NavDropdown title="Dropdown" id="basic-nav-dropdown">
                    <NavDropdown.Item href="#action/3.1">Action</NavDropdown.Item>
                    <NavDropdown.Item href="#action/3.2">Another action</NavDropdown.Item>
                    <NavDropdown.Item href="#action/3.3">Something</NavDropdown.Item>
                    <NavDropdown.Divider />
                    <NavDropdown.Item href="#action/3.4">Separated link</NavDropdown.Item>
                  </NavDropdown>
                </Nav>
              </Navbar.Collapse>
            </Navbar>

         <Route exact path="/"> 
            <Jumbotron className="background">
              <h1>20% Season OFF</h1>
              <p>
                This is a simple hero unit, a simple jumbotron-style component for calling
                extra attention to featured content or information.
            </p>
              <p>
                <Button variant="primary">Learn more</Button>
              </p>
            </Jumbotron>

            <div calssName="container">
            <div className="row"> { /* 12 칼럼으로 쪼갠다.*/ }
              { /* 한 칼럼이 4칸을 차지하도록 (md=mobile) */ }
              
              {
                shoes.map((curShoe, index)=> {
                  return <ProductCard curShoe={ curShoe } key={ index }/>
                })
              }
              
            </div>
          </div>      
         </Route>
          <Route path="/detail">   
              { Detail }
          </Route>

          {/* <Route path="~~~" component={ Modal }></Route> */}

          
        </div>
      );
    }

    index.js 소스

    import React from 'react';
    import ReactDOM from 'react-dom';
    import './index.css';
    import App from './App';
    import reportWebVitals from './reportWebVitals';

    import { BrowserRouter } from 'react-router-dom';

    ReactDOM.render(
      <React.StrictMode>
        <BrowserRouter>
          <App />
        </BrowserRouter>
      </React.StrictMode>,
      document.getElementById('root')
    );

    // If you want to start measuring performance in your app, pass a function
    // to log results (for example: reportWebVitals(console.log))
    // or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
    reportWebVitals();

     

    강의 따라가면서 진행해서 셋팅은 잘 되어있는거 같아요.

    #8451

    codingapple
    키 마스터

    <Route path=”/detail”>   
              <Detail/>
    </Route>

    이렇게써보십시오

    #8453

    김관영
    참가자

    해결됐습니다.

    감사합니다. 코딩애플님 !

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

About

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

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

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