inflearn logo
강의

강의

N
챌린지

챌린지

멘토링

멘토링

N
클립

클립

로드맵

로드맵

지식공유

따라하며 배우는 노드, 리액트 시리즈 - 쇼핑몰 사이트 만들기[전체 리뉴얼]

더보기 버튼이 안 보입니다

272

notbackdown

작성한 질문수 5

0

안녕하세요 선생님 좋은 강의 잘 듣고 있습니다

이미지를 8개 이상 업로드 한 후

제가 더보기 버튼 만들기 #1과 #2를 들었는데 

코드를 다 작성하고 보니까 나중에 더보기 버튼이 사라졌습니다

제가 작성한 코드는 아래와 같습니다

웹에서 더보기 버튼을 누르지도 않았는데

왜 더보기 버튼이 사라졌는지 파악이 안 되네요ㅜㅜ

============================================================================================

=============================================================================================

routes 에 있는 product.js 코드

const express = require('express');
const router = express.Router();
const multer = require('multer');
const { Product } = require('../models/Product');
// Product

var storage = multer.diskStorage({
    destination: function (reqfilecb) {
        cb(null'uploads/')
    },
    filename: function (reqfilecb) {
        cb(null`${Date.now()}_${file.originalname}`)
    }
})
   
  var upload = multer({ storage: storage }).single("file")

router.post('/image', (reqres)=> {
    // 가져온 이미지를 저장 해주면 된다.
    upload(reqreserr => {
        if(err) {
            return req.json({success: falseerr})
        }
        return res.json({success: truefilePath:res.req.file.pathfileName: res.req.file.filename })
    })

})

router.post('/', (reqres)=> {
    //    받아온 정보들을 DB에 넣어 준다.

    const product = new Product(req.body);

    product.save((err=> {
        if(errreturn res.status(400).json({ success: falseerr})
        return res.status(200).json({ success: true})
    })
})


router.post('/products', (reqres)=> {
    //  product collection에 들어 있는 모든 상품 정보들을 가져오기

    let limit = req.body.limit ? parseInt(req.body.limit) : 20;
    let skip = req.body.skip ? parseInt(req.body.skip) : 0;

    Product.find()
        .populate("writer")
        .skip(skip)
        .limit(limit)
        .exec((errproductInfo)=> {
            if(errreturn res.status(400).json({ success: falseerr})   

            return res.status(200).json({ 
                success: trueproductInfo,
                postSize: productInfo.length})
        })
    
})


module.exports = router;

=============================================================================================

LandingPage.js 에 있는 코드

import React, {useEffectuseStatefrom 'react'
import { FaCode } from "react-icons/fa";
import axios from "axios";
import {IconColCardRowCarouselfrom 'antd';
import Meta from 'antd/lib/card/Meta';
import ImageSlider from '../../utils/ImageSlider';


function LandingPage() {
    
    const [ProductssetProducts] = useState ([])
    const [SkipsetSkip] = useState(0)
    const [LimitsetLimit] = useState(8)
    const [PostSizesetPostSize] = useState(0)
   
    useEffect(() => { 
        
        let body = {
            skip: Skip,
            limit: Limit
        }

        getProducts(body)
       
    }, [])

    const getProducts = (body=> {
        axios.post('/api/product/products'body)
        .then(response => {
            if(response.data.success) {
                if(body.loadMore) {
                    setProducts([...Products, ...response.data.productInfo])
                } else {
                    setProducts(response.data.productInfo)
                }
                setPostSize(response.data.PostSize)
            } else {
                alert("상품들을 가져오는데 실패 했습니다.")
            }
        })
    }
    
    const loadMoreHandler = () => {
        
        let skip = Skip + Limit

        let body = {
            skip: skip,
            limit: Limit,
            loadMore: true
        }

        getProducts(body)
        setSkip(skip)
    }

    const renderCards = Products.map((productindex)=> {

        return <Col lg={6} md={8} xs={24} key={index} >
            <Card
                 cover={<ImageSlider images={product.images}/>}
               >
                <Meta 
                    title={product.title}
                    description={`$${product.price}`}
                />
            </Card> 
         </Col>    
    })
    
    
    
    return (
       <div style={width: '75%'margin: '3rem auto'}}>

           <div style={textAlign: 'center'}}>
             <h2>Let's Travel Anywhere <Icon type="rocket" /></h2>
           </div>
           
           {/* Filter */}

            {/* Search */}

            {/* Cards */}

            <Row gutter={[1616]} >
                 {renderCards}
            </Row>
            
            <br />
            
                {PostSize >= Limit &&
                    <div style={display: 'flex'justifyContent: 'center'}}>
                        <button onClick={loadMoreHandler}> 더보기 </button>
                    </div>
                }

       </div>
    )
}

export default LandingPage

=============================================================================================

ImageSlider.js에 있는 코드 

import React from 'react'
import {IconColCardRowCarouselfrom 'antd';


function ImageSlider(props) {
    return (
        <div>
          <Carousel autoplay>
            
            {props.images.map((imageindex=> (
                <div key={index}>
                    <img style={{width: '100'maxHeight:'150px'}}
                        src={`http://localhost:5000/${image}`} />
                </div>
            ))}

          </Carousel>
        </div>
    )
}

export default ImageSlider

react redux nodejs 웹앱 mongodb

답변 2

1

notbackdown

LandingPage.js 에 있는 setPostSize(response.data.PostSize)의 PostSize와

routes에 있는 Product.js에 있는 return res.status(200).json({

success: true, productInfo,

postSize: productInfo.length}) 의 postSize가 같지 않아서 안 되었네요

routes에 있는 Product.js의 postSize를 PostSize로 바꿔주니 해결되었습니다

0

John Ahn

해결하시느라 수고하셨습니다 ~!!!! 

강의 내용은 훌륭하나, 환경 설정 오류 때문에 진도를 나갈 수 없습니다. 20년 버전 강의.

0

60

1

강의자료는 어디서 볼 수있나요??

0

66

1

이 쇼핑몰 만들기 강의는 관리자페이지 만드는건 없나요

0

113

2

웹에서 실시간 코드반영이 안돼요

0

120

1

app.use질문

0

64

1

강사님께 어떻게 직접질문할수있어요??

0

75

1

const함수같은거 기초강의는 어디있나요

0

81

2

리덕스 참조챕터가 어딨어요? 미리듣고오라는데요

0

81

2

강의가완전 오래되서 다 틀리네 app.jsx도 tailwind css 다틀림 무책임함

0

68

1

개발자도구에 redux란이 없어요

0

87

1

npx tailwindcss init -p 에서 계속 에러나요

0

92

1

쇼핑몰기능중 찜하기 기능은 어떻게 구현하나요

0

138

2

강의하다 줌으로 설명가능한지좀 정확히 알려주세요. 이 선생님 정책이 어떻게 되는데요. 직접 연락할 메일이라도 알려주세요

0

42

1

도표 강의 자료 열람 불가능

0

109

1

tailwindcss를 vite에서 이용하는 방식이 바뀐것 같습니다.

0

1130

2

eslint 설정 후 오류가 납니다.

0

221

1

오버로드 오류

0

149

1

VSCode에서 save를 할 때, landingpage의 useEffect가 실행되는 문제에 대하여

0

169

1

dispatch(logoutUser()) 실행시 dispatch(authuser())도 함께 실행되는 문제

0

228

2

logout할 때, server로 요청을 보내서 authUser middleware를 통과하도록 하는 이유?

0

195

1

webkit-text-size-adjust 오류

0

314

1

does not provide an export named 'userReducer'

0

216

2

빌드 배포

0

140

1

삭제 예정 강의는 언제 삭제 되나요? 저것때문에 수강완료를 못하면 회사에서 비용을 청구한다고 합니다~

0

220

2