this.state.array.push('value');
이런 식으로 push를 사용했는데, 리액트에서는 그러면 안된다.
import React, { Component } from 'react';
import PhoneForm from './components/PhoneForm';
class App extends Component {
id = 2
state = {
information: [
{
id: 0,
name: '김민준',
phone: '010-0000-0000'
},
{
id: 1,
name: '홍길동',
phone: '010-0000-0001'
}
]
}
handleCreate = (data) => {
const { information } = this.state;
this.setState({
information: information.concat({ id: this.id++, ...data })
})
}
render() {
const { information } = this.state;
return (
<div>
<PhoneForm
onCreate={this.handleCreate}
/>
{JSON.stringify(information)}
</div>
);
}
}
export default App;
모르는 내용
//사용예
const array1 = ['a', 'b', 'c'];
const array2 = ['d', 'e', 'f'];
const array3 = array1.concat(array2);
console.log(array3);
// expected output: Array ["a", "b", "c", "d", "e", "f"]
2)비구조화 할당(구조분해 할당)
객체나 배열을 변수로 분해 할수 있게 해주는 문법
객체나 배열에 저장된 데이터 전체가 아닌 일부만 필요한 경우 유용
또는 함수의 매개변수가 많거나 매개변수 기본값이 필요한 경우 등에 유용
2-1) 배열 분해하기
// 이름과 성을 요소로 가진 배열
let arr = ["Bora", "Lee"]
// 구조 분해 할당을 이용해
// firstName엔 arr[0]을
// surname엔 arr[1]을 할당.
let [firstName, surname] = arr;
alert(firstName); // Bora
alert(surname); // Lee
let [name1, name2, ...rest] = ["Julius", "Caesar", "Consul", "Roman"];
alert(name1); // Julius
alert(name2); // Caesar
// `rest`는 새롭게 생성된 배열임.
alert(rest[0]); // Consul
alert(rest[1]); // Roman
alert(rest.length); // 2
rest는 나머지 요소를 담은 새로운 배열이 됨.
rest 대신 다른 이름을 사용해도 되는데, 변수 앞에 점 3개 꼭 넣고, 변수가 가장 마지막에 위치해야 함.
3-1) 객체 분해하기
구조 분해 할당으로 객체도 분해할 수 있음.
//기본문법
let {var1, var2} = {var1:…, var2:…}
//예시
let options = {
title: "Menu",
width: 100,
height: 200
};
let {title, width, height} = options;
alert(title); // Menu
alert(width); // 100
alert(height); // 200
let options = {
title: "Menu",
width: 100,
height: 200
};
// { 객체 프로퍼티: 목표 변수 }
let {width: w, height: h, title} = options;
// width -> w
// height -> h
// title -> title
alert(title); // Menu
alert(w); // 100
alert(h); // 200
let options = {
title: "Menu",
height: 200,
width: 100
};
// title = 이름이 title인 프로퍼티
// rest = 나머지 프로퍼티들
let {title, ...rest} = options;
// title엔 "Menu", rest엔 {height: 200, width: 100}이 할당됩니다.
alert(rest.height); // 200
alert(rest.width); // 100
3) JSON.stringify(value)
JSON.stringfiy(value); //문자열로 변환된 데이터값
map 함수 잠깐 알아보기
//기본 문법
arr.map(callback(currentValue[, index[, array]])[, thisArg])
//예시
const array1 = [1, 4, 9, 16];
// pass a function to map
const map1 = array1.map(x => x * 2);
console.log(map1);
// expected output: Array [2, 8, 18, 32]