computed property name

김민석·2021년 5월 21일
0

JS

목록 보기
3/5
let i = 0;
let a = {
  ["foo" + ++i]: i,
  ["foo" + ++i]: i,
  ["foo" + ++i]: i
};
let i = 'hi';
let a = {
  ["foo" + i]: i,
};
console.log(a.foohi) // hi

이런게 가능하다.

딱 이걸 생각하면 된다.

foo["foohi"]

이 구문을 객체를 정의할 때도 쓸 수 있는 것!


이걸 편하게 쓸 수 있을 때가 있는데 바로....

react에서 input value를 핸들링 할 때!

const [id, setId] = useState("");
const [password, setPassword] = useState("");

const onChangeId = useCallback((e) => {
	setId(e.target.value);
}, []);

const onChangePassword = useCallback((e) => {
	setPassword(e.target.value);
}, []);

원래 이런 식으로 설정해줬던 것을....

 const [inputs, setInputs] = useState({
    id: "",
    password: "",
  });
  const onChangeInputs = useCallback((e) => {
    const { name, value } = e.target;
    setInputs((inputs) => {
      return { ...inputs, [name]: value };
    });
  }, []);

이렇게 한 번에 설정이 가능해졌다.

굿!

0개의 댓글