inflearn logo
강의

강의

N
챌린지

챌린지

멘토링

멘토링

N
클립

클립

로드맵

로드맵

지식공유

묻고 답해요

172만명의 커뮤니티!! 함께 토론해봐요.

pojo 에 setter 가 없는 경우가 있을까요?

해결됨

실전 jOOQ! Type Safe SQL with Java

안녕하세요 강사님. jooq 강의 잘 듣고 있습니다. 현재 update 부분 강의를 들으면서 실습해보고 있는데 Actor 에 setter 메소드들이 없어서 dao 를 통한 update를 하는데 다소 어려움이 생겼습니다. insert 의 경우는 생성자에 데이터를 넣어서 잘 넘어갔는데, update 에서는 setter 가 없으니까, insert 한 값을 Actor 객체로 반환 받아서 그 객체에 있는 setter 를 이용해 update 하는 방식이 불가능하다 보니 "setter 는 어디로 갔는가?" 생각이 들더라구요. 실습중인 jooq 버전은 3.19.5 이고, 아래는 Actor pojo 파일 구조 입니다.

  • java
  • sql
  • spring-boot
  • jooq
  • dsl
창랑 댓글 1 좋아요 1 조회수 214

2-16 ssg 구현중 에러입니다.

해결됨

한 입 크기로 잘라먹는 Next.js

안녕하세요 강사님, 강의를 듣는 중 문제가 발생해 글 남깁니다. book/id 상세페이지에서 SSG getStaticPaths를 적용중인데, id를 인식을 못해 에러가 발생합니다. Error: A required parameter (id) was not provided as an array received string in getStaticPaths for /book/[[...id]] 강의에 의하면, books/1 은 보여야 하는데 페이지가 보이지 않네요 오타인 것 같아 강사님 깃헙 코드도 복사해서 붙여봤는데 에러가 납니다 혹시 다른 문제가 있을까요? 에러 메세지에는 id가 제공이 안된다고 하는데, 제가 보기에는 staticProps에 맞게 변경한거 같은데, 왜 에러가 날까요??

  • react
  • typescript
  • next.js
나를응원해 댓글 2 좋아요 0 조회수 123

노드(express) 연동

해결됨

React 완벽 마스터: 기초 개념부터 린캔버스 프로젝트까지

유튜브에 올라온 js강의가 너무 만족스러워서 강의를 신청하였고, 현재 강의 잘듣고 있습니다. 저는 노드 공부를 하였고, 프론트 부분을 리액트로 하고 싶어서 강의를 듣고 있는데 혹시 노드(express)와 연동 해서 프로젝트를 하고 싶은데 괜찮은 자료나 강의가 있을까요?

  • react
  • React-Context
  • react-router
  • tailwindcss
  • react-query
철수 댓글 2 좋아요 0 조회수 151

한국어 더빙이 안되는것 같네요~

해결됨

[인프런 X VMware Tanzu] Spring Boot 밋업 with Josh Long

한국어 더빙이 안되는것 같은데요~ 다른 언어는 다 되는데 한국어를 선택하면 영어로 나오네요~

  • java
  • spring
  • spring-boot
이종석 댓글 1 좋아요 0 조회수 199

localhost:3000 ERR_CONNECTION_REFUSED

미해결

따라하며 배우는 노드, 리액트 시리즈 - 챗봇 사이트 만들기

npm run dev로 서버는 성공적으로 올라갔는데 localhost:3000 접속 시 연결이 거부되었다고 뜹니다. 이것저것 많이 찾아보긴 했는데 해결이 안되네요 ㅠㅠ windows, 크롬에서 실행했습니다. 해결 방법을 알 수 있을까요? // index.js const express = require("express"); const path = require("path"); const bodyParser = require("body-parser"); const app = express(); const config = require("./server/config/keys"); // const mongoose = require("mongoose"); // mongoose.connect(config.mongoURI, { useNewUrlParser: true, useUnifiedTopology: true }) // .then(() => console.log('MongoDB Connected...')) // .catch(err => console.log(err)); app.use(bodyParser.urlencoded({ extended: true })); app.use(bodyParser.json()); app.use('/api/dialogflow', require('./server/routes/dialogflow')); // Serve static assets if in production if (process.env.NODE_ENV === "production") { // Set static folder app.use(express.static("client/build")); // index.html for all page routes app.get("*", (req, res) => { res.sendFile(path.resolve(__dirname, "client", "build", "index.html")); }); } const port = process.env.PORT || 5000; app.listen(port, () => { console.log(`Server Running at ${port}`) }); //package.json { "name": "chatbot-app", "version": "1.0.0", "description": "chatbot-app", "main": "index.js", "engines": { "node": "18.20.5", "npm": "10.9.0" }, "scripts": { "start": "node index.js", "backend": "nodemon index.js", "frontend": "npm run front --prefix client", "dev": "concurrently \"npm run backend\" \"npm run start --prefix client\"" }, "author": "Jaewon Ahn", "license": "ISC", "dependencies": { "actions-on-google": "^3.0.0", "body-parser": "^1.20.3", "dialogflow": "^1.2.0", "dialogflow-fulfillment": "^0.6.1", "dotenv": "^16.4.5", "express": "^4.21.1", "mongoose": "^8.8.1", "node": "^18.20.5", "punycode": "^2.3.1" }, "devDependencies": { "@ant-design/icons": "^5.5.1", "@babel/plugin-proposal-private-property-in-object": "^7.21.11", "concurrently": "^9.1.0", "nodemon": "^3.1.7" } } client쪽 //package.json { "name": "client", "version": "0.1.0", "private": true, "dependencies": { "antd": "^4.24.16", "axios": "^1.7.7", "prop-types": "^15.8.1", "react": "^18.3.1", "react-dom": "^18.3.1", "react-redux": "^9.1.2", "react-router-dom": "^6.28.0", "react-scripts": "5.0.1", "redux": "^5.0.1", "redux-promise": "^0.6.0", "redux-thunk": "^3.1.0", "uuid": "^11.0.3" }, "scripts": { "start": "react-scripts start", "build": "react-scripts build", "test": "react-scripts test", "eject": "react-scripts eject" }, "eslintConfig": { "extends": "react-app" }, "browserslist": { "production": [ ">0.2%", "not dead", "not op_mini all" ], "development": [ "last 1 chrome version", "last 1 firefox version", "last 1 safari version" ] }, "devDependencies": { "http-proxy-middleware": "^3.0.3" } }

  • react
  • node.js
김유림 댓글 1 좋아요 0 조회수 985

Home이 화면에 안 떠요

해결됨

한 입 크기로 잘라 먹는 리액트(React.js) : 기초부터 실전까지

import "./App.css"; import { Routes, Route } from "react-router-dom"; import Home from "./pages/Home"; import Diary from "./pages/Diary"; import New from "./pages/New"; // 1. "/" : 모든 일기를 조회하는 Home 페이지 // 2. "/new" : 새로운 일기를 작성하는 New 페이지 // 3. "/diary" : 일기를 상세히 조회하는 Diary 페이지 function App() { return ( <Routes> <Route path="/" element={<Home />} /> <Route path="/new" element={<New />} /> <Route path="/diary" element={<Diary />} /> </Routes> ); } export default App; const Home = () => { return <div>Home</div>; }; export default Home; 이렇게 작성했고, 오타도 없는 것 같은데 화면에 home이라는 글자가 안 뜹니다. router도 6.28. 으로 설치됐습니다.

  • javascript
  • react
  • node.js
이연서 댓글 1 좋아요 0 조회수 175

이상한게 있습니다..

미해결

자바 ORM 표준 JPA 프로그래밍 - 기본편

학습하는 분들께 도움이 되고, 더 좋은 답변을 드릴 수 있도록 질문전에 다음을 꼭 확인해주세요. 1. 강의 내용과 관련된 질문을 남겨주세요. 2. 인프런의 질문 게시판과 자주 하는 질문(링크)을 먼저 확인해주세요. (자주 하는 질문 링크: https://bit.ly/3fX6ygx) 3. 질문 잘하기 메뉴얼(링크)을 먼저 읽어주세요. (질문 잘하기 메뉴얼 링크: https://bit.ly/2UfeqCG) 질문 시에는 위 내용은 삭제하고 다음 내용을 남겨주세요. ========================================= [질문 템플릿] 1. 강의 내용과 관련된 질문인가요? 예 2. 인프런의 질문 게시판과 자주 하는 질문에 없는 내용인가요? 예 3. 질문 잘하기 메뉴얼을 읽어보셨나요? 예 [질문 내용] 여기에 질문 내용을 남겨주세요. Team team = new Team(); team.setTeamNm("Team"); em.persist(team); Members members = new Members(); members.setName("good"); members.setHelloTeam(team); em.persist(members); em.flush(); em.clear(); Members finMembers = em.find(Members.class, members.getId()); List<Members> result = finMembers.getHelloTeam().getMembers(); System.out.println("aaaaaaaaaaaaaaaaaaaa="+result.size()); 뭔가 이상해요 em.flush(); em.clear(); 을 안쓰면 finMembers까지는 null 이 아닌데 results 까지는 null입니다. 왜 이런거예요 ???

  • java
  • jpa
junil jeong 댓글 2 좋아요 1 조회수 165

질문의 질 문의

미해결

실전! 스프링 부트와 JPA 활용1 - 웹 애플리케이션 개발

전에 질문 드린바와 같이(아래 링크 참조) https://www.inflearn.com/community/questions/1427027?focusComment=380094 private Date deliveryPlanDate; @Column(name = "delivery_plan_date") private Date planDate; 개발하는데 있어서 이런거에 너무 집착하는게 아닐까 걱정됩니다. 제가 경력이 4년(php만 사용)이어도 자바 백엔드 개발자로 농담삼아서 신분세탁하러 이직한다고 퇴사하고 자바, 스프링 공부 한답시고 직접 개발하면서 부족한 부분이 무엇인지 파악하고 복습하는 식으로 하는데, 저런 네이밍 규칙때문에 너무 발목을 잡고 있는거 같아 자괴감이 듭니다. 너무 쓸데 없는거에 집착하는건지 현실적으로 피드백 주시면 감사하겠습니다.

  • java
  • spring
  • 웹앱
  • spring-boot
  • jpa
댓글 2 좋아요 0 조회수 75

cover_image_tag(self) 부분 질문이 있습니다.

미해결

파이썬/장고 웹서비스 개발 완벽 가이드 with 리액트 (장고 4.2 기준)

안녕하세요 강사님. 인자로 받는 self는 그 c++의 this 포인터 같은 개념으로 보면 될까요, 그리고 list_display 안에 cover_image를 cover_image_tag로 바꿨는데 처음에 cover_image는 같은 클래스(SongAdmin)에 있는 함수라 list_display에서 사용가능한거고, cover_image_tag는 models 파일 안에 Song 클래스 안에 있는 함수라 list_display에서 사용이 가능한걸까요? 감사합니다.

  • react
  • python
  • django
  • web-api
  • htmx
sunnnwo 댓글 1 좋아요 0 조회수 79

[11-30] 강의 crispy form 적용에서 오류가 발생해서 관련 문의 드립니다.

해결됨

파이썬/장고 웹서비스 개발 완벽 가이드 with 리액트 (장고 4.2 기준)

강사님 안녕하세요, HTMX와 모달을 활용한 댓글 기능을 구현하는 코드 작성 중에 crispy form이 적용이 되지 않고 오류가 발생해서 문의드립니다. 작성하고 있던 코드는 _comment_form.html 파일의 코드입니다 아래 이미지는 발생한 에러 내용입니다. comment_form.html 파일의 코드를 구현하고 로컬호스트에 띄운 개별 Note 페이지의 하단에 '댓글 쓰기' 버튼을 클릭했을 때, crispy form이 렌더링 되지 않고 위와 같은 에러가 발생하는 케이스입니다. 제가 추측하는 것은 context 변수에 담긴 데이터에 문제가 있어서, flatten() 메서드가 동작하지 않아 발생하는 에러 같다고 생각하는데요. 해결하는 방법에 대해 알려주시면 감사하겠습니다! 감사합니다 🙂

  • react
  • python
  • django
  • web-api
  • htmx
천진한 댓글 3 좋아요 0 조회수 159

db컬럼 명과 class 멤버 명 통일성

미해결

실전! 스프링 부트와 JPA 활용1 - 웹 애플리케이션 개발

class Delivery { private Date deliveryPlanDate; @Column(name = "delivery_plan_date") private Date planDate; } 이럴땐 둘 중 어떤게 더 효율적인가요:?

  • java
  • spring
  • 웹앱
  • spring-boot
  • jpa
댓글 2 좋아요 0 조회수 108

OCP에서 궁금한게 있습니다.

미해결

김영한의 실전 자바 - 기본편

학습하는 분들께 도움이 되고, 더 좋은 답변을 드릴 수 있도록 질문전에 다음을 꼭 확인해주세요. 1. 강의 내용과 관련된 질문을 남겨주세요. 2. 인프런의 질문 게시판과 자주 하는 질문(링크)을 먼저 확인해주세요. (자주 하는 질문 링크: https://bit.ly/3fX6ygx) 3. 질문 잘하기 메뉴얼(링크)을 먼저 읽어주세요. (질문 잘하기 메뉴얼 링크: https://bit.ly/2UfeqCG) 질문 시에는 위 내용은 삭제하고 다음 내용을 남겨주세요. ========================================= [질문 템플릿] 1. 강의 내용과 관련된 질문인가요? (예/아니오) 2. 인프런의 질문 게시판과 자주 하는 질문에 없는 내용인가요? (예/아니오) 3. 질문 잘하기 메뉴얼을 읽어보셨나요? (예/아니오) [질문 내용] OCP를 공부하면서 궁금한점이 있습니다. Car 인터페이스를 implements 하는 GoodCar이라는 클래스에 Nav() 라는 네비게이션 기능을 추가하려면 Car 인터페이스에도 Nav()라는 함수를 추가해야 Driver가 사용가능할거 같습니다. 이러면 기존의 Car을 implements하는 클래스들이 매서드 미구현으로 에러가 발생합니다. 그래서 Car 인터페이스를 안바꾸려면 앞서 배운 fly 인터페이스처럼 따로 인터페이스를 만들면 구현은 가능할거 같은데, 이런 경우 OCP를 지킨다고 할 수 있나요? 아니면 다른 방법이 있을까요?

  • java
  • 객체지향
유승현 댓글 1 좋아요 0 조회수 97

부모 객체, 자식 객체에 대한 질문

미해결

자바 ORM 표준 JPA 프로그래밍 - 기본편

안녕하세요. 이번에 JPA 로드맵을 다시 한번 복습을 하면서 부모 객체, 자식 객체에 대한 궁금한 점이 생겼습니다. 부모 객체, 자식 객체 관계의 용어는 어떤 상황에서 사용해야 하는 건가요? 연관 관계도 아닌 것 같고.. 상속 관계도 아닌 것 같고.. (자바, 스프링 로드맵에서 강사님이 항상 강조하시는 말씀이 있죠. 부모는 ~ 품을 수 있지만 자식은 ~ 품을 수 없다. 근데 JPA에서는 전혀 다른 상황인 것 같아서요.) cascade와 orphanRemoval 기능을 사용하기 위해 cascade와 orphanRemoval 코드를 내부에 적은 객체 자체가 부모 객체가 되는 건가요? 예를 들면 @Entity @Table(name = "orders") @Getter @Setter @NoArgsConstructor(access = AccessLevel.PROTECTED) public class Order { @Id @GeneratedValue @Column(name = "order_id") private Long id; @ManyToOne(fetch = LAZY) @JoinColumn(name = "member_id") private Member member; @JsonIgnore @OneToMany(mappedBy = "order", cascade = CascadeType.ALL, orphanRemoval = true) private List<OrderItem> orderItems = new ArrayList<>(); @JsonIgnore @OneToOne(fetch = LAZY, cascade = CascadeType.ALL, orphanRemoval = true) @JoinColumn(name = "delivery_id") private Delivery delivery; ... ​위의 코드에서 cascade = CascadeType.ALL, orphanRemoval = true 기능을 사용해서 생명주기의 책임이 있는 Order 엔티티 객체가 부모 객체가 되고 OrderItem과 Delivery 엔티티 객체가 자식 객체가 되는건가요?

  • java
  • jpa
sparkyoon 댓글 1 좋아요 1 조회수 87

고급1편 안 듣고 고급2편 들어도 되나요?

미해결

김영한의 실전 자바 - 고급 2편, I/O, 네트워크, 리플렉션

고급2편 내용 먼저 들으려는데 멀티스레드 동시성 이거 무조건 들어야 고급 2편 들을 수 잇을까요?

  • java
  • 네트워크
  • 객체지향
tkadnd2242 댓글 2 좋아요 0 조회수 406

@Override

미해결

김영한의 실전 자바 - 기본편

[질문 내용] 자식 클래스에서 부모 클래스를 상속받아 변수를 새로 재정의 할 때 왜 변수에는 @Override 어노테이션을 사용 할 수 없는 건가요? 생각해보니까 메소드 오버라이딩은 있어도 자식클래스에서 부모클래스의 동일한 변수는 왜 재정의가 안되는 거죠?

  • java
  • 객체지향
soojinkimss 댓글 1 좋아요 0 조회수 107

재생이 안됩니다ㅠㅠ

미해결

나도코딩의 자바 기본편 - 풀코스 (20시간)

갑자기 모든 강의가 재생이 안됩니다ㅠㅠ

  • java
  • 객체지향
tjdals4358 댓글 2 좋아요 0 조회수 128

CORS - Access-Control-Allow-Origin 누락 문제

미해결

Slack 클론 코딩[실시간 채팅 with React]

강좌보면서 proxy 설정하고 back 폴더 npm run dev, alecture 폴더 npm run build 했는데 회원가입 버튼을 누르니 콘솔창에 시간차로 계속 Access to XMLHttpRequest at ' https://sleact.nodebird.com/api/users ' from origin ' http://localhost:3095 ' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. app.js:2 GET https://sleact.nodebird.com/api/users net::ERR_FAILED 200 (OK) (익명) @ app.js:2 e.exports @ app.js:2 e.exports @ app.js:2 l.request @ app.js:2 r.forEach.l.<computed> @ app.js:2 (익명) @ app.js:2 r.Z @ 678.js:1 (익명) @ app.js:2 (익명) @ app.js:2 (익명) @ app.js:2 (익명) @ app.js:2 o @ app.js:2 (익명) @ app.js:2 (익명) @ app.js:2 D @ app.js:2 [신규] Edge에서 Copilot을 사용하여 콘솔 오류 설명: 클릭 오류를 설명합니다. 자세한 정보 다시 표시 안 함 signup:1 Access to XMLHttpRequest at ' https://sleact.nodebird.com/api/users ' from origin ' http://localhost:3095 ' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. app.js:2 GET https://sleact.nodebird.com/api/users net::ERR_FAILED 200 (OK) (익명) @ app.js:2 e.exports @ app.js:2 e.exports @ app.js:2 l.request @ app.js:2 r.forEach.l.<computed> @ app.js:2 (익명) @ app.js:2 r.Z @ 678.js:1 (익명) @ app.js:2 (익명) @ app.js:2 (익명) @ app.js:2 (익명) @ app.js:2 o @ app.js:2 (익명) @ app.js:2 setTimeout onErrorRetry @ app.js:2 (익명) @ app.js:2 (익명) @ app.js:2 (익명) @ app.js:2 u @ app.js:2 Promise.then c @ app.js:2 (익명) @ app.js:2 o @ app.js:2 (익명) @ app.js:2 (익명) @ app.js:2 D @ app.js:2 signup:1 Access to XMLHttpRequest at ' https://sleact.nodebird.com/api/users ' from origin ' http://localhost:3095 ' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. 319.js:1 undefined app.js:2 POST https://sleact.nodebird.com/api/users net::ERR_FAILED라는 오류가 발생합니다. copilot을 실행시켜보니 Access-Control-Allow-Origin과 Origin이 같아야하는데 Access-Control-Allow-Origin 부분이 누락되었다고 나옵니다. 네트워크 200번대는 실행에는 성공한거라고 들었는데... 도움주시면 감사하겠습니다! 제 webpack.config.ts 첨부하겠습니다. import path from 'path'; //import ReactRefreshWebpackPlugin from '@pmmmwh/react-refresh-webpack-plugin'; import webpack, { Configuration as WebpackConfiguration } from "webpack"; import { Configuration as WebpackDevServerConfiguration } from "webpack-dev-server"; //import { BundleAnalyzerPlugin } from 'webpack-bundle-analyzer'; interface Configuration extends WebpackConfiguration { devServer?: WebpackDevServerConfiguration; } import ForkTsCheckerWebpackPlugin from 'fork-ts-checker-webpack-plugin'; const isDevelopment = process.env.NODE_ENV !== 'production'; const config: Configuration = { name: 'sleact', mode: isDevelopment ? 'development' : 'production', devtool: !isDevelopment ? 'hidden-source-map' : 'eval', resolve: { extensions: ['.js', '.jsx', '.ts', '.tsx', '.json'], alias: { '@hooks': path.resolve(__dirname, 'hooks'), '@components': path.resolve(__dirname, 'components'), '@layouts': path.resolve(__dirname, 'layouts'), '@pages': path.resolve(__dirname, 'pages'), '@utils': path.resolve(__dirname, 'utils'), '@typings': path.resolve(__dirname, 'typings'), }, }, entry: { app: './client', }, module: { rules: [ { test: /\.tsx?$/, loader: 'babel-loader', options: { presets: [ [ '@babel/preset-env', { targets: { browsers: ['IE 10'] }, debug: isDevelopment, }, ], '@babel/preset-react', '@babel/preset-typescript', ], env: { development: { plugins: [require.resolve('react-refresh/babel')], }, }, }, exclude: path.join(__dirname, 'node_modules'), }, { test: /\.css?$/, use: ['style-loader', 'css-loader'], }, ], }, plugins: [ // new ForkTsCheckerWebpackPlugin({ // async: false, // // eslint: { // // files: "./src/**/*", // // }, // }), new webpack.EnvironmentPlugin({ NODE_ENV: isDevelopment ? 'development' : 'production' }), ], output: { path: path.join(__dirname, 'dist'), filename: '[name].js', publicPath: '/dist/', }, devServer: { historyApiFallback: true, // react router port: 3090, devMiddleware: { publicPath: '/dist/' }, static: { directory: path.resolve(__dirname) }, proxy: { '/api/': { target: 'http://localhost:3095', changeOrigin: true, }, }, }, }; if (isDevelopment && config.plugins) { // config.plugins.push(new webpack.HotModuleReplacementPlugin()); // // config.plugins.push(new ReactRefreshWebpackPlugin()); // // config.plugins.push(new BundleAnalyzerPlugin({ analyzerMode: 'server', openAnalyzer: true })); } if (!isDevelopment && config.plugins) { // config.plugins.push(new webpack.LoaderOptionsPlugin({ minimize: true })); // // config.plugins.push(new BundleAnalyzerPlugin({ analyzerMode: 'static' })); } export default config;

  • react
  • 웹팩
  • typescript
  • socket.io
  • babel
  • 클론코딩
nayoung hwang 댓글 3 좋아요 0 조회수 473

인텔리제이 SDK 오류

미해결

김영한의 실전 자바 - 중급 2편

인텔리제이에서 java-mid2 폴더를 열면 파일들이 안보이는데 SDK 오류 같습니다. 어떤 버전의 SDK 써야 오류 안나나요? 지금은 Eclipse Termurin 21.0.4 -aarch64 설정되어 있네요

  • java
  • 객체지향
  • 코딩-테스트
  • 알고리즘
최연승 댓글 2 좋아요 0 조회수 181

한 엔티티에 같은 JoinColumn name이 있을경우 어떻게 처리하는지 궁금합니다.

미해결

실전! 스프링 부트와 JPA 활용1 - 웹 애플리케이션 개발

@ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "user_id") private User createUser; @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "user_id") private User lastModifyUser; DB 한 테이블에 글 등록 유저 정보와 마지막 수정 유저 정보를 넣도록 설계했는데 아래와 같이 안되면 이럴때는 보통 설계를 어떻게 하나요?? Caused by: org.hibernate.MappingException : Column 'user_id' is duplicated in mapping for entity 'study.factory.domain.Order' (use '@Column(insertable=false, updatable=false)' when mapping multiple properties to the same column)

  • java
  • spring
  • 웹앱
  • spring-boot
  • jpa
댓글 1 좋아요 0 조회수 92

12.11 invalid Date 오류

해결됨

한 입 크기로 잘라 먹는 리액트(React.js) : 기초부터 실전까지

따라서 하고 있었는데 다음 그림과 같이 invalid Date 라는 값이 떠서 관련 질문 드립니다. 강의 몇번 돌려보면서 오타가 있나 봤는데 도저히 모르겠어서 질문 드립니다... // App.jsx import "./App.css"; import { Routes, Route, Link, useNavigate } from "react-router-dom"; import Home from "./pages/Home"; import Diary from "./pages/Diary"; import New from "./pages/New"; import Edit from "./pages/Edit"; import Notfound from "./pages/Notfound"; import { useReducer, useRef, createContext } from "react"; const mockData = [ { id: 1, createdDate: new Date("2024-11-13").getTime(), emotionId: 1, content: "1번 일기 내용", }, { id: 2, createdDate: new Date("2024-11-10").getTime(), emotionId: 2, content: "2번 일기 내용", }, { id: 3, createdDate: new Date("2024-10-11").getTime(), emotionId: 3, content: "3번 일기 내용", }, ]; function reducer(state, action) { switch (action.type) { case "CREATE": return [action.data, ...state]; case "UPDATE": return state.map((item) => String(item.id) === String(action.data.id) ? action.date : item ); case "DELETE": return state.filter((item) => String(item.id) !== String(action.id)); default: return state; } } export const DiaryStateContext = createContext(); export const DiaryDispatchContext = createContext(); function App() { const [data, dispatch] = useReducer(reducer, mockData); const idRef = useRef(3); const onCreate = (createdDate, emotionId, content) => { dispatch({ type: "CREATE", data: { id: idRef.current++, createdDate, emotionId, content, }, }); }; const onUpdate = (id, createdDate, emotionId, content) => { dispatch({ type: "UPDATE", data: { id, createdDate, emotionId, content, }, }); }; const onDelete = (id) => { dispatch({ type: "DELETE", id, }); }; return ( <> <DiaryStateContext.Provider value={data}> <DiaryDispatchContext.Provider value={{ onCreate, onDelete, onUpdate }}> <Routes> <Route path="/" element={<Home />} /> <Route path="/new" element={<New />} /> <Route path="/diary/:id" element={<Diary />} /> <Route path="/edit/:id" element={<Edit />} /> <Route path="*" element={<Notfound />} /> </Routes> </DiaryDispatchContext.Provider> </DiaryStateContext.Provider> </> ); } export default App; //Home.jsx import { useState, useContext } from "react"; import { DiaryStateContext } from "../App"; import DiaryList from "../components/DiaryList"; import Header from "../components/Header"; import Button from "../components/button"; const getMonthlyData = (pivotDate, data) => { const beginTime = new Date( pivotDate.getFullYear(), pivotDate.getMonth(), 1, 0, 0, 0 ).getTime(); const endTime = new Date( pivotDate.getFullYear(), pivotDate.getMonth() + 1, 0, 23, 59, 59 ).getTime(); return data.filter( (item) => beginTime <= item.createdDate && item.createdDate <= endTime ); }; const Home = () => { const data = useContext(DiaryStateContext); const [pivotDate, setPivotDate] = useState(new Date()); const monthlyData = getMonthlyData(pivotDate, data); console.log(monthlyData); const onIncreaseMonth = () => { setPivotDate(new Date(pivotDate.getFullYear(), pivotDate.getMonth() + 1)); }; const onDecreaseMonth = () => { setPivotDate(new Date(pivotDate.getFullYear(), pivotDate.getMonth() - 1)); }; return ( <div> <Header title={`${pivotDate.getFullYear()}년 ${pivotDate.getMonth() + 1}월`} leftChild={<Button onClick={onDecreaseMonth} text={"<"} />} rightChild={<Button onClick={onIncreaseMonth} text={">"} />} /> <DiaryList data={monthlyData} /> </div> ); }; export default Home; //diaryList.jsx import Button from "./button"; import "./DiaryList.css"; import DiaryItem from "./DiaryItem"; const DiaryList = ({ data }) => { return ( <div className="DiaryList"> <div className="menu_bar"> <select> <option value={"latest"}>최신순</option> <option value={"oldest"}>오래된 순</option> </select> <Button text={"새 일기 쓰기"} type={"POSITIVE"} /> </div> <div className="list_wrapper"> {data.map((item) => ( <DiaryItem key={item.id} {...item} /> ))} </div> </div> ); }; export default DiaryList; //DiaryItem.jsx import { getEmotionImage } from "../util/get-emotion-image"; import Button from "./button"; import "./DiaryItem.css"; const DiaryItem = (id, emotionId, createdDate, content) => { return ( <div className="DiaryItem"> <div className={`img_section img_section_${emotionId}`}> <img src={getEmotionImage(1)} /> </div> <div className="info_seciton"> <div className="created_date"> {new Date(createdDate).toLocaleDateString()} </div> <div className="content">{content}</div> </div> <div className="button_section"> <Button text={"수정하기"} /> </div> </div> ); }; export default DiaryItem;

  • javascript
  • react
  • node.js
capstone24star 댓글 2 좋아요 0 조회수 166

인기 태그

인프런 TOP Writers

주간 인기글