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

home2 게시판 React 게시판 장바구니 기능 완성하기 가이드 에러 질문입니당

장바구니 기능 완성하기 가이드 에러 질문입니당

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

    김인환
    참가자

    에러 내용 : 

    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.

    소스 :

    app.js =

    import logo from './logo.svg';
    import {Navbar,Nav,NavDropdown,Form,FormControl,Button,Jumbotron} from 'react-bootstrap';
    import './App.css';
    import React, { useState } from 'react';
    import Data from './data.js';
    import Detail from './Detail.js'
    import { Link, Route, Switch, useHistory } from 'react-router-dom'
    import axios from 'axios';
    import { useContext } from 'react';
    import Cart from './Cart.js';

    export let 재고context = React.createContext();

    function App() {

      let [shoes, shoes변경] = useState(Data);
      let [재고, 재고변경] = useState([10]);

      return (
        <div className="App">
          <Navbar bg="light" expand="lg">
          <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 as={Link} to="/">Home </Nav.Link>
              <Nav.Link as={Link} to="/detail/2">Detail </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>
            <Form inline>
              <FormControl type="text" placeholder="Search" className="mr-sm-2" />
              <Button variant="outline-success">Search</Button>
            </Form>
          </Navbar.Collapse>
        </Navbar>

        <Switch>
          <Route exact path="/">
            <Jumbotron className="background">
              <h1>20% Seasom 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 className="container">

              <재고context.Provider value={재고}>

              <div className="row">
                {
                  shoes.map((a,i)=>{
                    return <Card shoes={a} i={i}/>
                  })
                }
              </div>
              </재고context.Provider>

              <button className="btn btn-primary" onClick={ ()=>{
                // axios.post('url',{id : 'preasim', pw : 1234}).then()

                axios.get('https://codingapple1.github.io/shop/data2.json')
                .then( (result)=>{
                  shoes변경( [...shoes, ...result.data] )
                } )
                
              } }>Learn more</button> 

            
            </div>
          </Route>

          <Route path="/detail/:id">

            <재고context.Provider value={재고}>
              <Detail shoes={shoes} 재고={재고} 재고변경={재고변경}/>
            </재고context.Provider>

          </Route>
          {/* <Route path="/어쩌구" component={Modal}></Route> */}

          <Route path="/cart">
            <Cart></Cart>
          </Route>

          
        </Switch>

        </div>
      );
    }

    function Card(props){
      let 재고 = useContext(재고context);
      let history = useHistory();
      return (
        <div className="col-md-4" onClick={()=>{history.push('/detail/'+props.shoes.id)}}>
          <img src={'https://codingapple1.github.io/shop/shoes' + (props.i+1) + '.jpg'} width="100%"/>
          <h4>{ props.shoes.title }</h4>
          <p>{ props.shoes.content } & { props.shoes.price }</p>

        </div>
      )
    }

    export default App;

    ----------------------------------------------------------------------------------------------------------------------------------

    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';
    import {Provider} from 'react-redux';
    import { combineReducers, createStore } from 'redux';

    let alert초기값 = true;

    function reducer2(state = alert초기값, 액션){
      if (액션.type === 'alert닫기'){
        state = false;
        return state;
      } else {
        return state;
      }
    }

    let 초기값 = [
      {id:0, name:'멋진신발', quan:2},
      {id:1, name:'멋진신발2', quan:1}
    ]

    function reducer(state = 초기값, 액션){
      
      if( 액션.type === '항목추가'){

        let copy = [...state];
          copy.push(액션.데이터);
          return copy

      } else if(액션.type === '수량증가'){
        let copy = [...state];
        copy[액션.데이터].quan++;
        return copy

      } else if (액션.type === '수량감소'){
        let copy2 = [...state];
        copy2[액션.데이터].quan--;
        return copy2
        
      } else {
        return state
      }
    }

    let store = createStore(combineReducers({reducer, reducer2}));

    ReactDOM.render(
      <React.StrictMode>
        <BrowserRouter>
          <Provider store={store}>
            <App />
          </Provider>
        </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();

     

    /cart에서 수량 변경 +,- 버튼을 누르면 계속 에러가 뜨는데 해결이 안됩니다..

    #13855

    codingapple
    키 마스터

    redux와 react-redux를 지웠다가 다시 설치해보는게 어떨까요 

    지우는건 npm uninstall 패키지명 이렇게 하면 됩니다

    #13869

    김인환
    참가자

    그래도 해결이 안 되는데 폴더를 새로 만들어 세팅을 첨부터 하는 게 나을까요?

    #13870

    codingapple
    키 마스터

    네 Invalid hook call 에러는 문법에러가 아니라면

    새로운 프로젝트 만들어서 테스트해보면 없어지는 경우가 많습니다

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

About

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

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

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