172만명의 커뮤니티!! 함께 토론해봐요.
해결됨
React + GPT API로 AI회고록 서비스 개발 (원데이 클래스)
GPT API 호출, 프롬프트 연동 강의 0:24 계속해서 useState에 다음과 같은 오류가 뜹니다. import { useState } from "react"; 오류 사유는'useState' is declared but its value is never read. 대체 왜 해결이 안되는 것일까요..?ㅜ.ㅜ
HTML/CSS javascript react node.js chatgpt
한나
2023-11-10T01:03:58.801Z
댓글 2
좋아요 1
조회수 836
미해결
실습으로 끝장내는 웹 크롤링과 웹 페이지 자동화 & 실전 활용
driver = webdriver.Chrome () 여기서 계속 오류가 나는데요. 혹시 최근에 바뀐게 있나요? 강의 내용 외 개인적인 실습 사이트의 질문은 답변이 제공되지 않습니다. 문제가 생긴 코드, 에러 메세지 등을 꼭 같이 올려주셔야 빠른 답변이 가능합니다. 코드를 이미지로 올려주시면 실행이 불가능하기 때문에 답변이 어렵습니다. 답변은 바로 제공되지 않을 수 있습니다. 실력 향상을 위해서는 직접 고민하고 검색해가며 해결하는 게 가장 좋습니다.
python 웹-크롤링 selenium beautifulsoup
니키부
2023-11-08T09:38:51.642Z
댓글 3
좋아요 0
조회수 1972
해결됨
[퇴근후딴짓] 빅데이터 분석기사 실기 (작업형1,2,3)
학습 관련 질문을 남겨주세요. 상세히 작성하면 더 좋아요! 질문과 관련된 영상 위치를 알려주면 더 빠르게 답변할 수 있어요 먼저 유사한 질문이 있었는지 검색해보세요 무게에서 - 120을 뺀 이유가 무엇인가요?
python 머신러닝 빅데이터 pandas 빅데이터분석기사
화이팅
2023-11-07T13:22:18.674Z
댓글 1
좋아요 0
조회수 320
미해결
[리뉴얼] 처음하는 파이썬 데이터 분석 (쉽게! 전처리, pandas, 시각화 전과정 익히기) [데이터분석/과학 Part1]
위 코드를 실행하니 'could not convert string to float: 'Abbeville' 라는 에러가 전시됩니다. Abbeville를 float으로 바꿀 수가 있나요?
이희동
2023-11-07T11:00:46.893Z
댓글 1
좋아요 0
조회수 310
해결됨
React + GPT API로 AI회고록 서비스 개발 (원데이 클래스)
setUserInput("")을 하면 userInput 값이 ""로 바뀌고 그다움 num 선언문에 ""의 숫자변환값이 들어가는게 아닌가 궁금합니다.
HTML/CSS javascript react node.js chatgpt
최지훈
2023-11-07T02:10:01.730Z
댓글 2
좋아요 2
조회수 348
미해결
[코드캠프] 부트캠프에서 만든 고농축 프론트엔드 코스
33-05 강의에서 test에서 자꾸 이 오류가 뜹니다 apis.js import { graphql } from "msw"; const gql = graphql.link("http://mock.com/graphql") export const apis = [ gql.mutation("createBoard", (req, res, ctx) => { const { writer, title, contents } = req.variables.createBoardInput return res( ctx.data({ createBoard: { _id: "qqq", writer, title, contents, __typepname: "Board", }, }) ); }), // gql.query("fetchBoards", () => {}) ]; jest.setup.js import { server } from "./src/commons/mocks/index" beforeAll(() => server.listen()); afterAll(() => server.close()); index.test.tsx import { fireEvent, render, screen, waitFor } from "@testing-library/react"; import StaticRoutingMovedPage from "../../pages/section33/33-05-jest-unit-test-mocking"; import { ApolloClient, ApolloProvider, HttpLink, InMemoryCache, } from "@apollo/client"; import fetch from "cross-fetch"; import mockRouter from "next-router-mock"; jest.mock("next/router", () => require("next-router-mock")); it("게시글이 잘 등록되는지 테스트 하자!", async () => { const client = new ApolloClient({ link: new HttpLink({ uri: "http://mock.com/graphql", fetch, }), cache: new InMemoryCache(), }); render( <ApolloProvider client={client}> <StaticRoutingMovedPage /> </ApolloProvider> ); fireEvent.change(screen.getByRole("input-writer"), { target: { value: "맹구" }, }); fireEvent.change(screen.getByRole("input-title"), { target: { value: "안녕하세요" }, }); fireEvent.change(screen.getByRole("input-contents"), { target: { value: "방가방가" }, }); fireEvent.click(screen.getByRole("submit-button")); await waitFor(() => { expect(mockRouter.asPath).toEqual("/boards/qqq"); }); }); 도와주십쇼 ㅠㅠ
react node.js seo graphql next.js
김무연
2023-11-03T07:22:46.450Z
댓글 4
좋아요 0
조회수 679
미해결
[개정판] 파이썬 머신러닝 완벽 가이드
강의 회귀 실습 1: 자전거 대여(공유) 수요 예측 -02에서 19분 52초 경에 나오는 선형 회귀의 피처별 회귀계수 시각화 부분에서 저 회귀계수 값들이 다르게 나올 수가 있는지, 질문드립니다. github의 주피터노트북 코드 다운로드 받아서 그대로 시행했는데 LinearRegression/Lasso/Ridge 각 회귀에 대한 RMSLE, RMSE, MAE까지는 값이 정확히 동일하게 나오는데 회귀 계수의 값을 보려고 lr_reg.coef_ 부분에서 결과가 다르게 나옵니다. 상식적으로 회귀 모형에서 이런 결과가 나올 수가 없다고 생각되는데 무슨 이유인지 모르겠어서 질문드립니다! 감사합니다
aloeeola
2023-11-02T11:52:36.722Z
댓글 3
좋아요 0
조회수 452
미해결
따라하며 배우는 리액트 네이티브 기초
<SafeAreaView> 써도 이러네요.. 환경은 윈도우, 안드로이드 스튜디오 pixel4 썼습니다
mozzzi.__
2023-11-02T09:48:31.927Z
댓글 3
좋아요 0
조회수 553
미해결
스프링 시큐리티 OAuth2
authenticastion Entry Point로 지정 시 cors문제가 계속해서 진행되어 Authorization Code를 받아올 수 없습니다. 코드 첨부 Authorization Server Config @Bean @Order(Ordered.HIGHEST_PRECEDENCE) public SecurityFilterChain authorizationServerSecurityFilterChain(HttpSecurity http) throws Exception { OAuth2AuthorizationServerConfiguration.applyDefaultSecurity(http); http .getConfigurer(OAuth2AuthorizationServerConfigurer.class) .oidc(Customizer.withDefaults() ); http .exceptionHandling((exceptions) -> exceptions .authenticationEntryPoint( new LoginUrlAuthenticationEntryPoint("http://localhost:3000") // new LoginUrlAuthenticationEntryPoint("/login") )) http.oauth2ResourceServer((resourceServer) -> resourceServer .jwt(Customizer.withDefaults())); return http.build(); } @Bean public RegisteredClientRepository registeredClientRepository() { RegisteredClient oidcClient = RegisteredClient.withId(UUID.randomUUID().toString()) .clientId("oidc-client") .clientSecret("{noop}secret") .clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC) .authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE) .authorizationGrantType(AuthorizationGrantType.REFRESH_TOKEN) .redirectUri("https://oidcdebugger.com/debug") .redirectUri("https://test-b821b.web.app") .postLogoutRedirectUri("http://127.0.0.1:8080/") .scope(OidcScopes.OPENID) .scope(OidcScopes.PROFILE) .clientSettings(ClientSettings.builder().requireAuthorizationConsent(true).build()) .build(); return new InMemoryRegisteredClientRepository(oidcClient); } @Bean public AuthorizationServerSettings authorizationServerSettings() { return AuthorizationServerSettings.builder().issuer("http://localhost:6080").build(); } } Default Web Config @Bean public WebMvcConfigurer corsConfigurer() { return new WebMvcConfigurer() { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/**") .allowedOrigins("http://localhost:3000") .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS") .allowedHeaders("*") .allowCredentials(true) .exposedHeaders("*"); } }; } @Bean public CorsConfigurationSource corsConfigurationSource() { CorsConfiguration configuration = new CorsConfiguration(); configuration.setAllowCredentials(true); configuration.addAllowedHeader("*"); configuration.addAllowedMethod("*"); configuration.addAllowedOrigin("http://localhost:3000"); configuration.setExposedHeaders(Arrays.asList("*")); UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); source.registerCorsConfiguration("/**", configuration); return source; } @Bean public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { http .cors(customCorsConfig -> customCorsConfig.configurationSource(corsConfigurationSource())) .csrf(AbstractHttpConfigurer::disable) .authorizeHttpRequests(authorizeHttpRequestsCustomizer -> authorizeHttpRequestsCustomizer.requestMatchers(AUTH_WHITELIST).permitAll() .anyRequest().authenticated() ) .formLogin( httpSecurityFormLoginConfigurer -> httpSecurityFormLoginConfigurer.loginPage("http://localhost:3000").loginProcessingUrl("/login") // Customizer.withDefaults() ) ; return http.build(); } @Bean public UserDetailsService userDetailsService() { PasswordEncoder passwordEncoder = new BCryptPasswordEncoder(); UserDetails userDetails = User.builder() .username("user") .password(passwordEncoder.encode("password")) .roles("USER") .build(); return new InMemoryUserDetailsManager(userDetails); } @Bean public JWKSource<SecurityContext> jwkSource() { KeyPair keyPair = generateRsaKey(); RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic(); RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate(); RSAKey rsaKey = new RSAKey.Builder(publicKey) .privateKey(privateKey) .keyID(UUID.randomUUID().toString()) .build(); JWKSet jwkSet = new JWKSet(rsaKey); return new ImmutableJWKSet<>(jwkSet); } private static KeyPair generateRsaKey() { KeyPair keyPair; try { KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA"); keyPairGenerator.initialize(2048); keyPair = keyPairGenerator.generateKeyPair(); } catch (Exception ex) { throw new IllegalStateException(ex); } return keyPair; } @Bean public JwtDecoder jwtDecoder(JWKSource<SecurityContext> jwkSource) { return OAuth2AuthorizationServerConfiguration.jwtDecoder(jwkSource); } @Bean public PasswordEncoder encoder() { return new BCryptPasswordEncoder(); } 위 코드로 진행했을 시 발생하는 Cors Error입니다 Access to XMLHttpRequest at 'http://localhost:6080/oauth2/authorize?client_id=oidc-client&redirect_uri=https%3A%2F%2Foidcdebugger.com%2Fdebug&scope=openid&response_type=code&response_mode=form_post&state=3it6dl9kewr&nonce=hyq3pnronj7&continue' (redirected from 'http://localhost:6080/login') from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. 3. 이로 인해 CorsFilter를 적용하게 되면 해당 Cors는 해결되지만 authorization code 가 Redirect되는 시점에 Cors 에러가 새롭게 나옵니다. CorsFilter @Component @Slf4j @Order(Ordered.HIGHEST_PRECEDENCE) public class CorsFilter implements Filter { private static final Set<String> allowedOrigins = new HashSet<String>(); static { allowedOrigins.add( "http://localhost:3000" ); } @Override public void init(FilterConfig fc) throws ServletException { } @Override public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { HttpServletResponse response = (HttpServletResponse) res; HttpServletRequest request = (HttpServletRequest) req; String origin = request.getHeader(HttpHeaders.ORIGIN); log.info("Origin: {}", origin); if (origin != null) { Optional<String> first = allowedOrigins.stream().filter(origin::startsWith).findFirst(); first.ifPresent(s -> response.setHeader("Access-Control-Allow-Origin", s)); } response.setHeader("Access-Control-Allow-Credentials", "true"); response.setHeader("Access-Control-Allow-Methods", "*"); response.setHeader("Access-Control-Max-Age", "3600"); response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Key, Authorization"); if ("OPTIONS".equalsIgnoreCase(request.getMethod())) { response.setStatus(HttpServletResponse.SC_OK); } else { chain.doFilter(req, res); } } @Override public void destroy() { } Cors 오류 Access to XMLHttpRequest at 'https://oidcdebugger.com/debug?code=1o_jSQQVu6EB4XDq-xCWP3qrzp2VDdGbH_AN7iBJGU5gQRC7BRFkQYdn2A6P-6G5Aoi8XLJLaVR4MSVktNzDvYLMmj_UXahcWfEwQdA-tk4GCw5Bff4mXn2q6mIYfs_d&state=3it6dl9kewr' (redirected from 'http://localhost:6080/login') from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. 혹시 외부 로그인 페이지와 연동한 예시가 있거나, Cors 문제를 해결할 방안이 있는지 궁금합니다ㅠㅠ
java spring spring-boot oauth react
2023-11-02T06:01:48.590Z
댓글 2
좋아요 0
조회수 829
미해결
[개정판] 파이썬 머신러닝 완벽 가이드
안녕하세요, 선생님. 강의 15분 경에 다음과 같은 코드가 나옵니다만, 저는 분명 동일한 코드를 실행했는데 오류가 떠서 질문드립니다. house_df.fillna(house_df.mean(),inplace = True) TypeError: can only concatenate str (not "int") to str 이 코드가 Null있는 문자형 열까지 포함시켜 처리하기 때문에 오류가 나는 거 같은데, 혹시 원래 정상적으로 실행되는 코드인가요…? 책에 있는 코드도 동일한데 제가 실행시키면 에러가 나서 전 Null 있는 숫자혀여 열에 대해서만 각 열의 평균값으로 결측치를 채워서 실행했습니다. 만약 현재 버젼으로 정상적으로 실행이 되지 않는 코드라면 선생님께서 혹시 이 부분에 대해서만 새로 작성하신 코드를 여쭙고 싶습니다! 방금 확인해보니까 jupyter notebook으로는 잘 실행되는데, vscode에서는 위와 같은 오류가 뜹니다. 혹시 이 오류가 뜨는 이유를 알 수 있을까요?
맹고
2023-11-02T05:01:27.183Z
댓글 1
좋아요 0
조회수 589
미해결
파이썬/장고 웹서비스 개발 완벽 가이드 with 리액트
강사님 안녕하세요 강사님 강의 덕분에 저 혼자서 페이지도 만들고 nginx 사용해서 서버까지 배포해보았습니다. 다름이 아니라 3일전 까지만 해도 느리긴 했지만 잘 되던 서버가 오늘 서버내의 기능을 사용할려고 하니 502 bad gateway를 내 뱉으면서 멈춰버립니다.(되다가 안되다가 반복함) 그래서 error 로그를 찾아보니 2023/11/01 00:20:22 [error] 10930#10930: *232 upstream prematurely closed connection while reading response header from upstream 라고 뜨네요 3일동안 해봤는데 헛발짓만 했네용.. gpt한테 물어봐도 메모리 리소스, 네트워크 문제 , 응답시간 문제 등 이라곤 하는데 메모리랑 네트워크에는 아무런 문제가 없는거 같습니다. 3일전까지만 해도 잘되던 서버가 안되니까 많이 답답하네요..
병주
2023-10-31T16:33:55.734Z
댓글 4
좋아요 0
조회수 718
해결됨
[코드캠프] 부트캠프에서 만든 고농축 백엔드 코스
리액트에서 fetchUser를 이용해 로그인이 되어있는지 검증하려고 하는데 로그인api를 호출 후 fetchUser를 호출하면 Unauthorized에러가 납니다 헤더에 토큰이 저장되지 않아서 그런걸까요?
javascript node.js docker rest-api nestjs graphql react
김선규
2023-10-29T09:06:50.525Z
댓글 1
좋아요 0
조회수 324
미해결
[코드캠프] 부트캠프에서 만든 고농축 프론트엔드 코스
안녕하세요 섹션 31 댓글 기능 구현 과제 중 궁금한 점이 있어 질문 남깁니다 댓글 리스트의 수정 아이콘 클릭 시 사진과 같은 화면이 나오도록 했고, 댓글 등록하기 presenter component를 재사용 했습니다 댓글 리스트 presenter 파일입니다 export default function CommentListUI(props) { return ( <S.Wrapper> {props.data?.fetchBoardComments.map((item) => ( <S.CommentListWrapper key={item._id}> {props.isEdit && props.commentId === item._id ? ( <CommentWriteUI></CommentWriteUI> ) : ( <S.Comment_Container> <S.profile_icon src="/02/profile_icon.png"></S.profile_icon> <S.Content_container> <S.Name_Star_container> <S.Text style={{ fontWeight: "600" }}>{item.writer}</S.Text> <S.ReviewStar_container style={{ marginLeft: "16px" }}> <S.StarDiv></S.StarDiv> <S.StarDiv></S.StarDiv> <S.StarDiv></S.StarDiv> <S.StarDiv></S.StarDiv> <S.StarDiv></S.StarDiv> </S.ReviewStar_container> </S.Name_Star_container> <S.Text style={{ marginTop: "-15px", fontWeight: "500" }}> {item.contents} </S.Text> <S.Text style={{ fontSize: "12px", fontWeight: "400", color: "#BDBDBD", }} > {getDate(item.createdAt)} </S.Text> </S.Content_container> <S.Icon_container> <S.Icon style={{ backgroundImage: `url("/createComment.png")` }} onClick={() => props.onClickTEST(item._id)} ></S.Icon> <S.Icon style={{ backgroundImage: `url("/clear.png")` }} onClick={() => props.onClickDelete(item._id)} ></S.Icon> </S.Icon_container> </S.Comment_Container> )} </S.CommentListWrapper> ))} </S.Wrapper> ); } 삼항연산자를 사용해 나오는 화면을 다르게 했습니다 isEdit 변수는 수정하기 아이콘 클릭 시 true로 바뀌고, 삼항연산자 조건에 isEdit 변수만 사용하니 수정 아이콘을 클릭하지 않은 다른 댓글 리스트가 사라지면서 재사용한 댓글 등록 presenter 파일만 화면에 나와서 조건은 위와 같이 작성했습니다 여기서 문제는 수정 아이콘을 클릭해 나오는 댓글 등록 창은 container 파일에 작성한 함수가 작동하지 않는 것입니다 댓글 리스트 container 파일입니다 export default function CommentList() { const { data } = useQuery(FETCH_COMMENTS); const [deleteBoardComment] = useMutation(DELETE_COMMENTS); const onClickDelete = async (item) => { const pw = prompt("비밀번호를 입력해주세요."); try { await deleteBoardComment({ variables: { pw: pw, boardCommentId: item, }, refetchQueries: [{ query: FETCH_COMMENTS }], }); alert("삭제되었습니다."); } catch (error) { alert(error.message); } }; // 수정하기 아이콘 클릭 시 화면 변화 const [isEdit, setIsEdit] = useState(false); const [commentId, setCommentId] = useState(); const onClickTEST = (item) => { setIsEdit(true); setCommentId(item); }; // console.log(commentId); return ( <CommentListUI data={data} onClickDelete={onClickDelete} onClickTEST={onClickTEST} isEdit={isEdit} commentId={commentId} ></CommentListUI> ); } 댓글 등록 container 파일입니다 const [updateBoardComment] = useMutation(UPDATE_BOARD_COMMENT); const onClickUpdate = () => { // updateBoardComment({ // variables: { // updateBoardCommentInput: { // contents: contents, // rating: 0 // }, // password: pw, // boardCommentId: // } // }) console.log("Test"); }; return ( <> <CommentWriteUI onChangeWriter={onChangeWriter} onChangePw={onChangePw} onChangeContents={onChangeContents} onClickUpdate={onClickUpdate} ></CommentWriteUI> </> ); } onClickUpdate 함수는 댓글 작성 presenter 파일의 등록하기 버튼에 연결되어 있습니다 상세 페이지 로딩 시 나오는 댓글 등록창은 버튼 클릭 시 콘솔이 제대로 나오는데 댓글 리스트 수정 아이콘을 눌러 나오는 댓글 등록창에서는 버튼을 눌러도 콘솔 자체가 나오지 않습니다 댓글 과제 가이드를 확인해서 어떻게 수정하면 좋을지는 알았지만, 궁금한 점이 해소되지 않네요 궁금한 점은 삼항연산자, map 등 기능의 속성을 제대로 알지 못한 채 사용한 문제인지 코드 자체를 잘못 작성한 것인지 추가로 rating(별점) 데이터 활용법에 대한 힌트를 얻고 싶습니다 rating 값 1 = 별 1개 인가요? rating 숫자 데이터가 별과 어떻게 연결되는지 잘 모르겠습니다 부족한 점이 많아 질문이 너무 길어졌네요 항상 감사합니다
react node.js seo graphql next.js
zero.1.0.one.xx
2023-10-28T14:43:05.606Z
댓글 2
좋아요 0
조회수 612
미해결
PHP 개발자의 최종 테크트리, 라라벨 강의
깃헙 주소 알려주시면 감사하겠습니다~
hanhee46
2023-10-28T07:24:00.681Z
댓글 1
좋아요 0
조회수 364
미해결
Airflow 마스터 클래스
WSL 설치시 하위시스템이 이미 설치되어있습니다. 라고 나오는데 Ubuntu 22.04.1 LTS는 없네요. 이미지 다운 어떻게 받아서 설치하나요?
poptato
2023-10-28T00:54:45.895Z
댓글 2
좋아요 0
조회수 919
미해결
[코드캠프] 부트캠프에서 만든 고농축 프론트엔드 코스
안녕하세요. test를 하던 중 오류가 발생하여 문의드립니다. 지금 현재 코드를 import { setupServer } from "msw/node"; import { apis } from "./apis"; export const server = setupServer(...apis); 위에처럼 입력해 놓은 상태입니다. 하지만 테스트 실행 시 아래와 같이 발생합니다. Cannot find module 'msw/node' from 'src/commons/mocks/index.js' Require stack: src/commons/mocks/index.js jest.setup.js > 1 | import { setupServer } from "msw/node"; | ^ 2 | import { apis } from "./apis"; 추가적으로 지금 jest관련 페이지에서 Parsing error: ESLint was configured to run on `<tsconfigRootDir>/src\commons\mocks\index.js` using `parserOptions.project`: <tsconfigRootDir>/tsconfig.json However, that TSConfig does not include this file. Either: - Change ESLint's list of included files to not include this file - Change that TSConfig to include this file - Create a new TSConfig that includes this file and include it in your parserOptions.project See the typescript-eslint docs for more info: https://typescript-eslint.io/linting/troubleshooting#i-get-errors-telling-me-eslint-was-configured-to-run-- 위와 같은 오류가 발생합니다. 해결 부탁드립니다!
react node.js seo graphql next.js
dlwjdgus3217
2023-10-25T15:51:27.424Z
댓글 2
좋아요 0
조회수 1279
미해결
파이썬 무료 강의 (활용편4) - 업무자동화 (RPA)
기본 명령어인 것 같은데 어째서 title만 어트리뷰트가 없다고 에러 뜰까요? 프로그램을 껐다 켜봐도 이렇습니다.. 파이선 3.8.6 버전 쓰고 있고 비주얼 스튜디오 코드는 1.83.1 버전 쓰고 있는 것 같네요
rpa 파이썬 openpyxl python python3
이예린
2023-10-22T06:34:49.470Z
댓글 1
좋아요 0
조회수 409
미해결
안녕하세요 react, redux, node.js를 활용하여 웹 앱 개발을 하려고 하는데 react의 경우 class형과 함수형 두 가지의 타입으로 개발이 되고 있더군요 그래서 함수형 react의 참고서를 찾아봤는데 참고할만한 교재를 선택하기에 어려움이 있어서 질문 드립니다. 혹시 추천해주실만한 참고서가 있을까요?
ymca1036
2023-10-18T01:13:06.542Z
댓글 1
좋아요 0
조회수 343
해결됨
[리뉴얼] 처음하는 파이썬 데이터 분석 (쉽게! 전처리, pandas, 시각화 전과정 익히기) [데이터분석/과학 Part1]
섹션7-2 5분 2초 apply부분에 apply(func, axis = 0)으로 하면 왜 '영어' 행이 하나 더 생기나요?
tjswn0125
2023-10-16T17:50:39.811Z
댓글 1
좋아요 0
조회수 315
해결됨
한 입 크기로 잘라 먹는 리액트(React.js) : 기초부터 실전까지
안녕하세요. 사용자 입력 처리하기 강의 관련 질문입니다. input 태그를 통해 사용자 입력을 받고, 상태 관리하면, 상태에 사용자의 입력이 반영되는 게 한 단계씩 늦는 것 같습니다. (그 이유가 useState가 비동기적으로 처리된다고 들은적이 있는 것 같은데, 정확히 이해가 가지 않아서 질문드립니다.) 아래 코드의 handleOnChange함수에서, Q1) e.target.name, e.target.value은 제깍제깍 실시간으로 반영이 되는데, input state는 한 단계 늦게 반영이 됩니다. 이런 현상이 발생하는 이유는 무엇이고, 이건 개발하는데 문제가 되지 않는 이유는 뭔지? 가 궁금합니다! import { useState } from 'react'; const DiaryEditor = () => { const [input, setInput] = useState({ author: '', content: '', emotion: 1, }); const handleOnChange = (e) => { console.log(e.target.name); console.log(e.target.value); setInput({ ...input, [e.target.name]: e.target.value }); console.log(input); }; const handleSubmit = () => { console.log(input); alert('오늘의 일기가 저장되었습니다!'); }; return ( <div className='DiaryEditor'> <h2>오늘의 일기</h2> <div> <input name='author' value={input.author} onChange={handleOnChange} /> <p>{input.author}</p> </div> <div> <textarea value={input.content} name='content' onChange={handleOnChange} /> <p>{input.content}</p> </div> <div> <span>감정 지수 : </span> <select onChange={handleOnChange} name='emotion' value={input.emotion} > <option value={1}>1</option> <option>2</option> <option>3</option> <option>4</option> <option value={5}>5</option> </select> </div> <div> <button onClick={handleSubmit}>저장하기</button> </div> </div> ); }; export default DiaryEditor; Q2) 위처럼 input이란 state는 한단계씩 늦게 반영이 되는데, select태그의 value 속성을 주는 목적은 무엇인가요?? 인풋의 value 속성은 실시간으로 인풋의 값과 상태를 동기화해주는 목적으로 사용한다고 생각했는데, state가 곧바로 변하지 않는거면, 이 인풋의 value 속성은 무용지물인 것 아닌가라는 생각이 들어 질문드립니다. <select onChange={handleOnChange} name='emotion' value={input.emotion} > Q3) useState의 초기값은 반드시 빈문자열등으로 인자를 전달하는 게 나은가요? 아무 인자도 전달하지 않으면 어떤 잠재적인 에러 발생 가능성이 있는건가요?
moon
2023-10-15T03:38:13.668Z
댓글 1
좋아요 0
조회수 617