본문 바로가기

전체 글138

[React] 클래스형 컴포넌트 LifeCycle 정리 생명주기 메서드 모든 컴포넌트는 다양한 종류의 생명주기 메소드를 가집니다. 그리고 이 메소드를 오버라이딩하여 특정 시점에 코드가 실행되도록 설정할 수 있습니다. import React from 'react'; import ReactDOM from 'react-dom'; import reportWebVitals from './reportWebVitals'; class Test extends React.Component{ constructor(props) { super(props); this.state = { name: 'jiwon', date: new Date() } } componentDidMount() { this.timerID = setInterval(() => this.tick(), 1000); /.. 2021. 12. 9.
TypeScript union타입, any타입, unknown 타입 let name1 :string = 'kim' let age :number = 25; let friend :null = null; //undefined, null 타입도 있음. let male :boolean = true; 변수에 타입지정이 가능하다는 것은 타입이 실수로 변경되는 것을 방지할 수 있는것을 의미한다. let arr : number[] = [123,456]; Array도 type을 지정하여 사용한다. 위 배열의 요소는 number만 올 수 있다. 유니온타입 Union Type let member : number | string = 'kim'; 유니온타입은 타입 2개 이상을 합쳐 새로운 타입을 만든다. member 변수에는 string, number 두가지 타입이 올 수 있다. 배열과 오브젝트.. 2021. 10. 25.
TypeScript 설치와 타입지정 설치 nodejs설치 VScode 터미널 오픈후 npm install -g typescript .ts 확장자인 파일하나를 생성한다. index.ts 생성 tsconfig.json 생성 //tsconfig.json { "compilerOptions": { "target" : "es5", "module" : "commonjs", } } 이 파일에 대해서는 나중에 알아볼 것이다. TypeScript 의 Type //index.ts let name1 = "kim"; ts파일은 브라우저가 읽을 수 없다. ts파일을 js파일로 변환해야사용할 수 있음. //index.ts let name2 :string = "park"; name2 = 123 타입스크립트는 변수에 type지정을 할 수 있다. name2라는 변수에는 .. 2021. 10. 24.
[백준 / 2164 / node.js] 카드 2 javascript 처음에는 그냥 class로 queue를 구현해서 동작시키려고 했다. let fs = require('fs'); let input = fs.readFileSync('/dev/stdin').toString().trim().split('\n'); const n = parseInt(input.shift()) class Queue { constructor(num){ this.arr = []; } enqueue(num){ this.arr.push(num); } drop(){ this.arr.shift(); } move(){ this.enqueue(this.arr.shift()) } length(){ return this.arr.length; } ans(){ return this.arr.shift(); } } con.. 2021. 9. 22.
Webpack이 뭔데!!(6) template engine을 webpack과 함께 사용해보기 Webpack이 바라보는 Module js sass hbs jpg, png hbs는 handlebars 의 약자로 이 확장자는 템플릿 엔진인handlebars가 사용하는 template 파일을 말합니다. 문서 내에 특정 데이터를 노출시켜야 할 때 직접 DOM을 파싱하고 데이터가 들어갈 공간을 찾아서 넣어주는 작업을 반복해야합니다. 이런 일을 많이해야할 때 템플릿 엔진을 사용합니다. 템플릿 엔진은 Model Template View 로 나눠져있습니다. Model은 문서에 노출시킬 데이터를 뜻하고 , Template 은 일반적인 문서와 비슷한데 모델이 갖고 있는 데이터가 어디에 어떻게 표현될 지 문서내에 작성이 되어있습니다. Model과 Temp.. 2021. 9. 14.
[프로그래머스/javascript] 짝지어제거하기 js 효율성검사 2번때문에 당황 했던 문제. 문제 자체는 어렵지않다. 배열을 하나 생성해주고 s를 쭉 순회하면서 배열에 담아준다. 그러면서 생성한 배열의 마지막 값과 현재 순회중인 s의 요소 값이 같으면 배열의 마지막 값을 pop해주고 다르면 현재값을 push해준다. function solution(s) { let tmp =[] let arr = [...s]; if(s.length % 2!==0) return 0 for(let cur of s){ if(tmp[tmp.length-1] === cur){ tmp.pop() }else{ tmp.push(cur) } } return !tmp.length ? 1 : 0; } 그리고 만약에 그 배열이 비어있으면 1을 리턴 하나라도 남아있으면 0을 리턴해주면된다. 여기서 .. 2021. 9. 1.
[webpack-cli] Invalid options object. Dev Server has been initialized using an options object that does not match the API schema. - options has an unknown property 'inline'. These properties are valid: object { allowedHosts?, bonjour?, client?, compre.. [webpack-cli] Invalid options object. Dev Server has been initialized using an options object that does not match the API schema. - options has an unknown property 'inline'. These properties are valid: object { allowedHosts?, bonjour?, client?, compress?, devMiddleware?, headers?, historyApiFallback?, host?, hot?, http2?, https?, ipc?, liveReload?, onAfterSetupMiddleware?, onBeforeSetupMiddlewar.. 2021. 8. 29.
[백준 / 1929 / nodejs] 소수구하기 javascript 소수 구하기 문제는 에라토스테네스의 체를 쓰거나 범위의 제곱근까지만 비교해서 찾는 방식이 대부분인 것 같아서 둘 다 해봤다. 1. 2~ 제곱근까지 나눠보기 let fs = require('fs'); let input = fs.readFileSync('/dev/stdin').toString().trim().split('\n'); const isPrime = (num) => { if(num === 1) return false; for(var i=2; iparseInt(e)); for(var i=n; iparseInt(e)); const arr = Array.from(Array(m+1).keys()) for(let i=2; i 2021. 8. 24.
[백준 / 1920/ nodejs] 수찾기 javascript nodejs로 풀었다. 처음시도했던 방식은 includes를 사용했다. let fs = require('fs'); let input = fs.readFileSync('/dev/stdin').toString().trim().split('\n'); const N = parseInt(input.shift()) const arr = input.shift().split(' '); const M = parseInt(input.shift()) const arrM = input.shift().split(' '); arrM.map( e => {arr.includes(e) ? console.log(1) : console.log(0)}) 결과는 시간초과 1. 이진탐색 그래서 이진탐색으로 시도해봤다. let fs = requ.. 2021. 8. 24.
TestDome React Image Gallery App 문제의 요구사항을 살펴보자. 이미지와 함께 X버튼이 존재하고 X버튼을 누르면 해당하는 이미지가 삭제되는 형태다. 1. 이미지 리스트 2. remove 버튼 눌렸을 때 삭제되게 ( 코드의 아랫쪽을 보면 첫번째 링크는 생성되자마자 remove가 클릭되게 되어있음) links라는 props를 전달하고 links는 배열형태. 이 말은 X Jsx에서는 class 말고 className을 그리고 img 태그도 꼭 닫아줘야한다. class ImageGallery extends React.Component { constructor(props) { super(props); this.state = { links: props.links }; this.remove = this.remove.bind(this); } remove.. 2021. 8. 21.
TestDome React Focusable Input 렌더링 될 때 shouldFocus prop이 true면 자동 포커스 되게끔 하면 되는 문제다. functional component이므로 useRef로 DOM에 접근해서 focus() 메서드를 사용하면 될 것 같다. 우선 문제의 요구사항은 1. shouldFocus가 true일 때 input focusing 2. 오직 첫 렌더링때만 input focuing 3. react hook 사용 const FocusableInput = (props) => { const inputRef = React.useRef(); React.useEffect(() => { if (props.shouldFocus) inputRef.current.focus(); }); return ; }; docum.. 2021. 8. 20.
TestDome React Change Username 문제에서 요구하는 사항을 보면 1. h1태그 사이에 value 값이 뜨게 2. 버튼을 누르면 input값을 읽어 Username 의 value를 변경 3. Reference Hook 사용해서 Username의 value update // React is loaded and is available as React and ReactDOM // imports should NOT be used class Username extends React.Component { state = { value: "" }; changeValue(value) { this.setState({ value }); } render() { const { value } = this.state; return {value}; } } functi.. 2021. 8. 20.