inflearn logo
강의

강의

N
챌린지

챌린지

멘토링

멘토링

N
클립

클립

로드맵

로드맵

지식공유

묻고 답해요

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

TypeError: Cannot read properties of undefined (reading 'map')

해결됨

비전공자를 위한 진짜 입문 올인원 개발 부트캠프

React로 웹 개발하기 - 2 수강후 에러 메시지 문의입니다. npm start 하여 로컬호스트 화면에 아래의 메시지가 나오는데 해결이 안됩니다. 어디에 문제가 있는건지 문의드립니다. &times; TypeError: Cannot read properties of undefined (reading 'map') MainPage C:/Users/hanthene/Documents/github/grab-market-web/src/main/index.js:33 30 | < img src = "images/banners/banner1.png" / > 31 | < / div > 32 | < h1 > 판매되는 상품들 < / h1 > > 33 | < div id = "product-list" > | ^ 34 | {products . map( function (product , index) { 35 | return ( 36 | < div className = "product-card" > View compiled ▶ 18 stack frames were collapsed. (anonymous function) C:/Users/hanthene/Documents/github/grab-market-web/src/main/index.js:15 12 | . then( function (result){ 13 | console . log(result) ; 14 | const products = result . data . products ; > 15 | setProducts(products) ; | ^ 16 | }) 17 | . catch ( function (error){ 18 | console . error( '에러 발생 : ' , error) ; View compiled This screen is visible only in development. It will not appear if the app crashes in production. Open your browser&rsquo;s developer console to further inspect this error. 에러가 나는 상태의 파일 그대로 GITHUB에 퍼블릭으로 올려놓았습니다. https://github.com/ucoder-git/grab-market-client 아래는 package.json 입니다. { "name" : "grab-market-web" , "version" : "0.1.0" , "private" : true , "dependencies" : { "@testing-library/jest-dom" : "^5.16.3" , "@testing-library/react" : "^12.1.4" , "@testing-library/user-event" : "^13.5.0" , "axios" : "^0.26.1" , "react" : "^17.0.2" , "react-dom" : "^17.0.2" , "react-scripts" : "^2.1.3" , "web-vitals" : "^2.1.4" }, 아래는 src폴더의 index.js 파일입니다. import React from 'react' ; import './index.css' ; import axios from "axios" ; function MainPage () { const [ products , setProducts ]= React . useState ([]); React . useEffect ( function () { axios . get ( "https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js" ) . then ( function ( result ){ console . log ( result ); const products = result . data . products ; setProducts ( products ); }) . catch ( function ( error ){ console . error ( '에러 발생 : ' , error ); }); }, []); return ( < div > < div id = "header" > < div id = "header-area" > < img src = "images/icons/logo.png" /> </ div > </ div > < div id = "body" > < div id = "banner" > < img src = "images/banners/banner1.png" /> </ div > < h1 > 판매되는 상품들 </ h1 > < div id = "product-list" > { products . map ( function ( product , index ) { return ( < div className = "product-card" > < div > < img className = "product-img" src = { product . imageUrl } /> </ div > < div className = "product-contents" > < span className = "product-name" > { product . name } </ span > < span className = "product-price" > { product . price } 원 </ span > < div className = "product-seller" > < img className = "product-avatar" src = "images/icons/avatar.png" /> < span > { product . seller } </ span > </ div > </ div > </ div > ); }) } </ div > </ div > < div id = "footer" ></ div > </ div > ); } export default MainPage ;

  • jsx
  • react
  • react-native
  • react
  • express
  • tensorflow
  • nodejs
  • 머신러닝 배워볼래요?
  • javascript
  • HTML/CSS
o2cornholdings 댓글 1 좋아요 0 조회수 530

늦은시간에 죄송합니다.

해결됨

풀스택 리액트 토이프로젝트 - REST, GraphQL (for FE개발자)

강의를 듣다가.. 제 수준에 당황에서 글을 남깁니다.. 혹시 이번강의(routes의 정의)가 이해가 되지 않는다면 어느파트를 집중해서 공부해야하는지 여쭤보고 싶습니다. 처음에는 막연하게 리액트, 타입스크립트를 공부하고 서버쪽 기초를 배우고 싶어, 그래프 큐엘과 아폴로등을 공부하기 위해 강의를 신청햇는데 기본적인 개념조차 안잡혀있는 제자신을 확인 할 수 있는 기회가 되었습니다 ㅠㅠ.. 수업과 관련이 없는 내용이지만 노드js를 공부한 후 듣는 편이 좋을까요 .. 아니면 어디를 공부하여야 할까요.. 답변 기다리겠습니다.

  • rest-api
  • react
  • graphql
ezdar 댓글 2 좋아요 0 조회수 276

JS 객체 강의에서 메모리에 관해 질문 드립니다.

해결됨

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

강의 15분 대에 객체 프로퍼티 속성을 delete하면 결국 삭제가 된 상태이고, 브라우저에서는 더이상 콘솔 로그를 찍어도 알 수가 없습니다. 그러나 왜 여전히 메모리가 삭제 되지 않았는지 그 의미가 이해되지 않아 질문을 드립니다.

  • javascript
  • nodejs
  • react
JINSUNG LEE 댓글 1 좋아요 0 조회수 245

copyList

해결됨

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

안녕하세요 강의 듣는 중 궁금한점이 생겨서 질문을 드리게 됩니다. 영상 24:32 부분에서 const copyList = JSON.parse(JSON.stringify(diaryList)); 으로 하셧는데 원본 배열을 정렬을 하게되어 불변성 문제 때문에 Json.stringify 로 문자열로 바꿧다가 다시 JSON.parse로 새로운 배열을 만들어 값을 받았는데 혹시 그럼 스프레드 연산자인 const copyList = [...diaryList] 이렇게 하게 된다면 위 코드와 다르게 동작이 될까요..?

  • javascript
  • nodejs
  • react
정준영 댓글 1 좋아요 1 조회수 336

질문이있습니다!

해결됨

풀스택 리액트 토이프로젝트 - REST, GraphQL (for FE개발자)

안녕하세요! 선생님! params와 query에 대해서 질문이 있습니다. delete 해줄때 client단에서는 params안에 id를 담아서 보내주고 server단에서는 query로 id를 받아야한다고 말씀하셨는데 params로 보내고 params로 받는건 안되는건가요???

  • graphql
  • react
  • rest-api
bj2525 댓글 1 좋아요 0 조회수 203

코드 질문이요

미해결

[리뉴얼] React로 NodeBird SNS 만들기

10:00분에서 useEffect(() => { if (!(me && me.id) { Router.push('/'); } }, [me &&.id]); if (!me) { return null; }; 이 코드를 if (!me) { Router.push('/'); return null; }; 이렇게 코드 바꿔도 오류는 없던데 밑에 껄로해도 별 차이 없는건가요?

  • react
  • express
  • redux
  • nodejs
  • Next.js
dsfsdf 댓글 1 좋아요 4 조회수 229

19강 3:34초처럼 나오질 않네요 디버그창에

미해결

작정하고 장고! Django로 Pinterest 따라만들기 : 바닥부터 배포까지

run-edit configurations 왼쪽 상단+ 눌러서 python 체크- 스크립트 패스 프래그매틱 -venv-scripts 파라미터 runserver 한다음 매니지파이 우클릭 디버깅(무당벌레) 누르면 원래 python manage.py runserver 한것처럼 127:0:0:1:8000 이런거 터미널 창에 안뜨는데. 사이트는 들어가지긴 해요 여기서 빈칸에 test 입력한다음 post 누르면 3:34초 처럼 디버그 창에 아무것도 안뜨네요 ㅠㅠ 그리고 디버깅 실행 눌르면 무담벌레 점 잠깐 찍혔다가 사라지네요

  • docker
  • django
  • python
coding corgi 댓글 0 좋아요 0 조회수 304

크롤링 중 list index out of range 에러 도움 부탁드립니다

미해결

제가 작성한 코드는 아닙니다 크롤링 하는 와중에 list index of range 에러가 나오는데 해결법을 못 찾아서 질문드립니다.. from urllib.request import urlopen from bs4 import BeautifulSoup from xml.dom.pulldom import END_DOCUMENT import pandas as pd import requests from bs4 import BeautifulSoup from datetime import datetime import re from tqdm import tqdm from tqdm.contrib.concurrent import process_map import math from time import sleep from multiprocessing.dummy import Pool import multiprocessing as mp from multiprocessing.pool import MaybeEncodingError start_date = "y1=2019&m1=09&d1=25" end_date = "y2=2019&m2=09&d2=30" url = "https://find.mk.co.kr/new/search.php?pageNum={}&cat=&cat1=&media_eco=&pageSize=10&sub=all&dispFlag=OFF&page=news&s_kwd=%BB%EF%BC%BA%C0%FC%C0%DA&s_page=news&go_page=&ord=1&ord1=1&ord2=0&s_keyword=%BB%EF%BC%BA%C0%FC%C0%DA&period=p_direct&s_i_keyword=%BB%EF%BC%BA%C0%FC%C0%DA&s_author=&{}&{}&ord=1&area=ttbd" def get_list(idx) : #idx = 검색했을때 page 번호 req = requests.get(url.format(idx, start_date, end_date)) #한글깨져서 인코딩 soup = BeautifulSoup(req.content.decode('euc-kr','replace'), 'html.parser') div_list = soup.find_all('div', {'class' : 'sub_list'}) art_list = [i.find('span', {'class': 'art_tit'}) for i in div_list] #db에 저장할거 title, href, body, date df = pd.DataFrame(columns = {'title','href', 'date','body'}) for article in art_list: append_flag = True title = str(article.find("a").contents[0]) href = str(article.find("a")["href"]) body_text = None date = None try: req = requests.get(href, timeout=2) except requests.exceptions.Timeout as errd: print("Timeout Error : ", errd) except requests.exceptions.ConnectionError as errc: print("Error Connecting : ", errc) except requests.exceptions.HTTPError as errb: print("Http Error : ", errb) # Any Error except upper exception except requests.exceptions.RequestException as erra: print("AnyException : ", erra) try: soup = BeautifulSoup(req.content.decode('euc-kr','replace'), 'html.parser') except: print("parser error") date_text = soup.find('li', {'class' : 'lasttime'}) if not date_text : date_text = soup.find('li', {'class' : 'lasttime1'}) if date_text : match = re.search(r'\d{4}.\d{2}.\d{2}', date_text.string) if match : date = datetime.strptime(match.group(), '%Y.%m.%d').date() else : print("match none") else : append_flag = False #print("mssing date text") art_text = soup.find('div', {'class' : 'art_txt'}) if not art_text : art_text = soup.find('div', {'class' : 'article_body'}) if not art_text : art_text = soup.find('div', {'class' : 'view_txt'}) if art_text : body_text = art_text.get_text() else : append_flag = False #print("mssing body text") #print("link : " + href) if append_flag : temp = pd.DataFrame({'title' : [ title ], 'href' : [ href ], 'date' : [ date ], 'body' : [body_text]}) df = df.append(temp) return df def get_count() : req = requests.get(url.format(1, start_date, end_date)) #한글깨져서 인코딩 soup = BeautifulSoup(req.content.decode('euc-kr','replace'), 'html.parser') count_text = soup.find('span', {'class' : 'class_tit'}).get_text().replace(",","") art_count = re.search("\d+",count_text) "y1=2019&m1=03&d1=15" print(start_date[3:7]+"년 "+start_date[11:13]+"월 "+start_date[17:]+"일 부터 " +end_date[3:7]+"년 "+end_date[11:13]+"월 "+end_date[17:]+"일 까지 총 " +art_count.group(0)+"개의 기사") return art_count.group(0) if __name__ == "__main__": count = get_count() tasks_count = math.ceil(float(count)/20) + 1 #tasks = range(1,10) tasks = range(1,tasks_count) result_list = process_map(get_list, tasks,max_workers=4) df = pd.concat(result_list) #df = pd.concat(parmap.map(get_list, tasks, pm_pbar = True, pm_processes = 4)) print(df) file_name = start_date[5:7]+start_date[11:13]+start_date[17:]+"_"+end_date[5:7]+end_date[11:13]+end_date[17:] df.to_csv(file_name+'.csv', index = False, encoding='utf-8-sig') ------------------------------------------------------------------------------------------------------------------------------------------------------ 코드는 이렇구요 _RemoteTraceback Traceback (most recent call last) _RemoteTraceback : """ Traceback (most recent call last): File "/home/ubuntu/anaconda3/envs/python3/lib/python3.6/concurrent/futures/process.py", line 175, in _process_worker r = call_item.fn(*call_item.args, **call_item.kwargs) File "/home/ubuntu/anaconda3/envs/python3/lib/python3.6/concurrent/futures/process.py", line 153, in _process_chunk return [fn(*args) for args in chunk] File "/home/ubuntu/anaconda3/envs/python3/lib/python3.6/concurrent/futures/process.py", line 153, in <listcomp> return [fn(*args) for args in chunk] File "<ipython-input-7-167ab35f9166>", line 22, in get_list title = str(article.find("a").contents[0]) IndexError: list index out of range """ The above exception was the direct cause of the following exception: IndexError Traceback (most recent call last) <ipython-input-7-167ab35f9166> in <module> () 96 #tasks = range(1,10) 97 tasks = range ( 1 , tasks_count ) ---> 98 result_list = process_map ( get_list , tasks , max_workers = 4 ) 99 df = pd . concat ( result_list ) 100 #df = pd.concat(parmap.map(get_list, tasks, pm_pbar = True, pm_processes = 4)) /home/ubuntu/anaconda3/envs/python3/lib/python3.6/site-packages/tqdm/contrib/concurrent.py in process_map (fn, *iterables, **tqdm_kwargs) 128 tqdm_kwargs = tqdm_kwargs . copy ( ) 129 tqdm_kwargs [ "lock_name" ] = "mp_lock" --> 130 return _executor_map ( ProcessPoolExecutor , fn , * iterables , ** tqdm_kwargs ) /home/ubuntu/anaconda3/envs/python3/lib/python3.6/site-packages/tqdm/contrib/concurrent.py in _executor_map (PoolExecutor, fn, *iterables, **tqdm_kwargs) 74 map_args . update ( chunksize = chunksize ) 75 with PoolExecutor ( ** pool_kwargs ) as ex : ---> 76 return list ( tqdm_class ( ex . map ( fn , * iterables , ** map_args ) , ** kwargs ) ) 77 78 /home/ubuntu/anaconda3/envs/python3/lib/python3.6/site-packages/tqdm/notebook.py in __iter__ (self) 255 def __iter__ ( self ) : 256 try : --> 257 for obj in super ( tqdm_notebook , self ) . __iter__ ( ) : 258 # return super(tqdm...) will not catch exception 259 yield obj /home/ubuntu/anaconda3/envs/python3/lib/python3.6/site-packages/tqdm/std.py in __iter__ (self) 1183 1184 try : -> 1185 for obj in iterable : 1186 yield obj 1187 # Update and possibly print the progressbar. /home/ubuntu/anaconda3/envs/python3/lib/python3.6/concurrent/futures/process.py in _chain_from_iterable_of_lists (iterable) 364 careful not to keep references to yielded objects . 365 """ --> 366 for element in iterable : 367 element . reverse ( ) 368 while element : /home/ubuntu/anaconda3/envs/python3/lib/python3.6/concurrent/futures/_base.py in result_iterator () 584 # Careful not to keep a reference to the popped future 585 if timeout is None : --> 586 yield fs . pop ( ) . result ( ) 587 else : 588 yield fs . pop ( ) . result ( end_time - time . monotonic ( ) ) /home/ubuntu/anaconda3/envs/python3/lib/python3.6/concurrent/futures/_base.py in result (self, timeout) 430 raise CancelledError ( ) 431 elif self . _state == FINISHED : --> 432 return self . __get_result ( ) 433 else : 434 raise TimeoutError ( ) /home/ubuntu/anaconda3/envs/python3/lib/python3.6/concurrent/futures/_base.py in __get_result (self) 382 def __get_result ( self ) : 383 if self . _exception : --> 384 raise self . _exception 385 else : 386 return self . _result --------------------------------------------------------------------------------------------------------------------- 이렇게 에러가 뜹니다 title = str(article.find("a").contents[0]) 이 부분에서 contents가 존재하지 않는데 인덱스로 접근하려고 해서 오류가 난 것 같은데 contents가 무조건 존재 하는게 아니라면 존재하지 않는 경우의 예외처리를 추가하려면 어떻게 해야될까요? 어느 위치에 뭐라고 작성해야 할지 몰라서 막막해서 질문드립니다

  • python
  • crawling
Co Di 댓글 0 좋아요 0 조회수 633

안녕하세요 리액트 최적화 관련하여 질문드립니다.

해결됨

프론트엔드 개발자를 위한, 실전 웹 성능 최적화(feat. React) - Part. 2

안녕하세요. 웹 최적화 파트1,2 수강자입니다. 수강을 하면서 웹에 대해 최대한 성능 좋게 개발을 꾸준히 하려고 노력하고 있습니다. 이에 따라 여러 가지 고민이 되는 부분이 생겨서 해당 카테고리와는 크게 관련성은 없지만 여기에 글을 올려봅니다. 궁금증 1. useMemo, useCallback 관련하여 질문드리고 싶습니다. memoization을 통해 불필요한 렌더링을 줄일 수 있는 장점을 가지고 있어 위와 같은 훅을 잘 사용해보려합니다. 하지만 효율적으로 사용을 해야 메모리 적으로 봤을 때 문제가 되지 않을거같아 고민을 하는 찰라에 많은 개발자분들이 단순히 useState에서 set하는 부분만을 useCallback에 담아서 사용하는거 같더라구요. 예를 들어 const [ isOpen, setIsOpen = useState<boolean>(false); const callback = useCallback( () => {setIsOpen(true)}, []); 이런 식으로요. 하지만 제 생각에는 이렇게 작은 것도 다 넣으면 모든게 메모리에 올라가게 되어 메모리 낭비인가 라는 생각이들었습니다. 이러한 작은 것들도 다 useMemo나 useCallback 을 적용하는 것이 메모리적인 관점에서 보는 것보다 렌더링에 이점을 주는 것이 더 큰가라는 생각이 듭니다. 혹시 이 부분에 대해 피드백 해주시면 감사하겠습니다. 궁금증 2. 많은 input에서의 onChange에 따른 렌더링 회원가입 폼과 같이 input 굉장히 많은 경우 여기에 onChange Event에 따라 회원정보가 set이 되고 타이핑할 때마다 리렌더링이 된다는 생각이 과하다는 생각이들어서 질문 드립니다. 그래서 제가 생각해본건 useRef로 모든 input에 접근하고 회원가입 버튼 눌렀을 때 한번에 input value 를 가져와서 한번만 set을 하는게 낫지않을까 라는 생각도 들었습니다. 위와 같은 생각이 잘못되었는지, 혹은 onChange에 따라 set을 다해도 가상돔으로 비교해서 전체 다 그려주는게 아니기 때문에 큰 이슈는 되지않아 그냥 사용해도 될지에 대해 궁금합니다. 답변해주시면 정말 감사하겠습니다.

  • devtools
  • react
유상원 댓글 1 좋아요 2 조회수 1478

질문이욤

미해결

[신규 개정판] 이것이 진짜 크롤링이다 - 기본편

- 학습 관련 질문을 남겨주세요. 상세히 작성하면 더 좋아요! - 먼저 유사한 질문이 있었는지 검색해보세요. - 서로 예의를 지키며 존중하는 문화를 만들어가요. - 잠깐! 인프런 서비스 운영 관련 문의는 1:1 문의하기를 이용해주세요. import requests from bs4 import BeautifulSoup import openpyxl fpath = r'C:\Users\Lenovo\Desktop\content\참가자_data.xlsx' wb = openpyxl.load_workbook(fpath) ws=wb.active #현재 활성화된 시트 선택 codes = ["000660","035720","005930"] row=2 for code in codes: url=f"https://finance.naver.com/item/sise.naver?code={code}" response = requests.get(url) html=response.text soup=BeautifulSoup(html,'html.parser') price=soup.select_one("#_nowVal").text price=price.replace(',','') print(price) ws=[f'B{row}']=int(price) row=row+1 wb.save(fpath) cannot assign to f-string expression 이런 에러가 뜨면서 작동이 안됩니다 ㅜㅜ

  • 웹-크롤링
  • python
댓글 1 좋아요 1 조회수 305

질문이요 ㅠㅠ

미해결

[신규 개정판] 이것이 진짜 크롤링이다 - 기본편

- 학습 관련 질문을 남겨주세요. 상세히 작성하면 더 좋아요! - 먼저 유사한 질문이 있었는지 검색해보세요. - 서로 예의를 지키며 존중하는 문화를 만들어가요. - 잠깐! 인프런 서비스 운영 관련 문의는 1:1 문의하기를 이용해주세요. 안녕하세요 강의 잘 듣고있습니다 다름이 아니라 엑셀부분을 코드 짜고 실행하면 엑셀 파일은 만들어지는데 안에 데이터셀이 텅 비어있습니다...ㅠㅠ

  • 웹-크롤링
  • python
댓글 1 좋아요 1 조회수 186

중첩함수 질문 수정

미해결

프로그래밍 시작하기 : 파이썬 입문 (Inflearn Original)

- 학습 관련 질문을 남겨주세요. 상세히 작성하면 더 좋아요! - 먼저 유사한 질문이 있었는지 검색해보세요. - 서로 예의를 지키며 존중하는 문화를 만들어가요. - 잠깐! 인프런 서비스 운영 관련 문의는 1:1 문의하기를 이용해주세요. def nested_func(num): #1 def func_in_func(num): #2 print(num) #3 print("In func") #4 func_in_func(num + 100) #5 nested_func(100) #6 수업 중 중첩함수에 관한 내용에서 #6를 먼저 받고 #1로 돌아가 num에 100이 입력된다는 것은 이해했습니다. 그런데 그다음에 #2로 가서 num에 100이 입력되지 않고 바로#4로 간다는 부분이 잘 와닿지 않습니다. 왜그렇게 되는건가요?

  • python
가나다라 댓글 4 좋아요 0 조회수 300

데이터 타입에 관련된 질문입니다.

미해결

[파이토치] 실전 인공지능으로 이어지는 딥러닝 - 기초부터 논문 구현까지

안녕하세요 호형님의 강의를 기본베이스로 듣고, 인터넷에서 이것저것 보면서 1D CNN을 제가 가진 데이터셋 분류에 적용하고있는 학생입니다. CustomDataSet을 만들고 DataLoader구현 후, 훈련과 검증, 테스트를 거치는 코드를 작성하였는데요. 훈련과 검증단계에서는 문제없이 진행되나 다른 섹션을 만들어 테스트코드를 돌리는중 type에러가 발생하였습니다. 왜 같은 dataset과 dataloader인데 test셋에서만 이런 문제가 나타나는건지 알고싶습니다. # 강의질문이 아니라 문제가 된다면 지우겠습니다ㅠㅠ

  • python
  • pytorch
  • 인공신경망
  • 딥러닝
  • pytorch
  • python
  • 머신러닝 배워볼래요?
정지원 댓글 1 좋아요 0 조회수 292

클라이언트에서 db를 가져오려면

미해결

따라하며 배우는 노드, 리액트 시리즈 - 기본 강의

안녕하세요 선생님 유익한 강의 잘 수강하고있습니다. 현재 회원가입까지 구현이 다 되어서 몽고 db에 회원가입시 데이터가 잘 들어가는것도 확인하였고, 클라이언트(프론트) 상에서 이 db를 가져와서 쓰고싶은데 어떻게 해야 가져와서 쓸수있을까요? 프론트만 파서 이쪽은 잘 감이 안잡힙니다 감사합니다.

  • nodejs
  • react
댓글 1 좋아요 0 조회수 186

logout시 오류페이지가 뜹니다

미해결

작정하고 장고! Django로 Pinterest 따라만들기 : 바닥부터 배포까지

- 학습 관련 질문을 남겨주세요. 상세히 작성하면 더 좋아요! - 먼저 유사한 질문이 있었는지 검색해보세요. - 서로 예의를 지키며 존중하는 문화를 만들어가요. - 잠깐! 인프런 서비스 운영 관련 문의는 1:1 문의하기를 이용해주세요. logout버튼을 누르면 404오류가 뜨면서 디버그를 false로 변경하라는 오류메시지가 뜨길래 settings.py에서 아래처럼 설정을 하였습니다. DEBUG = False ALLOWED_HOSTS = ['localhost','127.0.0.1'] 그리고 다시 로그아웃을 하니 지금은 아래와 같은 오류가 뜨고요 ㅠ 어떻게 해야될까요?

  • python
  • django
  • docker
Hady 댓글 3 좋아요 0 조회수 599

UnboundLocal Error: local variable referenced before assignmnet

해결됨

우리를 위한 프로그래밍 : 파이썬 중급 (Inflearn Original)

- 학습 관련 질문을 남겨주세요. 상세히 작성하면 더 좋아요! - 먼저 유사한 질문이 있었는지 검색해보세요. - 서로 예의를 지키며 존중하는 문화를 만들어가요. - 잠깐! 인프런 서비스 운영 관련 문의는 1:1 문의하기를 이용해주세요. c = 30 # global variable(전역 변수) def func_v3(a): print(a) print(c) c = 40 # local variable(지역 변수) # 위 코드를 실행했을 때, UnboundLocal Error가 발생하지만, c = 30 def func_v3(a): c = 40 # local variable(지역 변수) print(a) print(c) func_v3(10) 10 40 # 말씀하신 대로 이렇게 작성하면 Error가 발생하지 않고, 10과 40으로 출력된다는 건 이해했습니다. # 전역 변수보다 지역 변수를 우선시한다는 것 그런데 c = 40 을 print(c) 아래에 두었을 때와 위에 두었을 때, 이 위치가 파이썬 인터프리터가 바라보는 인식의 차이를 모르겠습니다. 이 내용을 구글링도 하고, [stackoverflow](https://stackoverflow.com/questions/10851906/python-3-unboundlocalerror-local-variable-referenced-before-assignment) 에도 들어가서 확인했지만, 이에 대한 확실한 설명은 없었습니다. 다들 이 문제에 대한 해결책으로 global 을 작성하면 되지만, 이는 나중에 디버깅을 힘들게 만들기 때문에 추천하지 않는다는 내용만 확인했습니다. 이에 대해 알려주시면 감사하겠습니다.

  • python
  • django
김제하 댓글 1 좋아요 0 조회수 815

JSX에 대한 질문드립니다.

해결됨

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

안녕하세요. JSX에서 문법규칙에서 반드시 부모 요소 하나가 감싸는 형태여야 한다라고 하는데 부모 요소가 무엇인지 알수 있을까요?

  • javascript
  • nodejs
  • react
고요한 댓글 1 좋아요 0 조회수 765

If Ture에서 조건은?

미해결

프로그래밍 시작하기 : 파이썬 입문 (Inflearn Original)

안녕하세요, if True : print('Good') 에서, Ture를 판단하는게 무엇인가요? 조건이 어떤건지 모르겠습니다. 참인지 거짓인지 판단하려면 대상(object)이 있어야 하지 않나요??

  • python
jaeho.park2 댓글 2 좋아요 2 조회수 268

DiaryEditor 페이지 date가 이상하게 받아져요

해결됨

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

신규글을 등록할 때에도 제일 밑으로가지고, 기존 글을 수정해도 밑으로 가지길래 Components로 확인해보니 date값이 다르게 들어가져요.. 더미데이터로 넣은 date는 1648092529386 ~ 90 인데 새로운글이나 수정글은 date가 1648080000000 로 나오네요ㅠㅠ onCreate랑 OnEdit이 DiaryEditor.js에서 date를 가져가기에 console . log ( new Date ( date ) . getTime ()) ; DiaryEditor.js 안에서 onCreate,onEdit 안에서 쓰는 getTime으로 찍어보면 1648080000000 나오는데 어디서 꼬인걸까요 ...? ㅠ https://codesandbox.io/s/sharp-brown-p38cvp?file=/src/components/DiaryEditor.js

  • react
  • nodejs
  • javascript
정중한 사슴 댓글 2 좋아요 0 조회수 277

postman에서 전송했을 때 무한 로딩이 해결이 안됩니다. 다른분들 방식도 안됩니다

미해결

따라하며 배우는 노드, 리액트 시리즈 - 기본 강의

안녕하세요. 강의 잘 보고 있습니다 제가 토큰 생성까지 따라했는데 무한로딩이 발생했습니다. if(err) return cb(err);로 수정을 했는데도 계속 로딩이 발생하네요 save함수 안에서는 console.log도 안찍히는 거 봐선 save함수가 문제인거 같기도 한데 검색해도 아무 정보도 안나와서 정말 답답하네요.. 혹시 도와주실수 있을까 해서 git hub 주소 올려봅니다 https://github.com/ChyoPyoRo/CP1

  • 무한로딩
  • generationToken
  • nodejs
  • react
댓글 1 좋아요 0 조회수 572

인기 태그

인프런 TOP Writers

주간 인기글