리덕스 액션객체 리터럴 내부에서 createAction 사용 시 self 참조

Felix Yi·2020년 3월 16일
0

상황과 필요

actions, reducers 를 분리해서 사용하는 일반적인 리덕스 패턴에서 redux-actions 의 createAction 을 사용한 리팩토링 진행 중 actions 객체 내부에서 자기 자신을 참조 시 undefine 오류 발생. 따라서 객체 리터럴 내부에서 self 를 참조할 수 있는 방법 필요.

import {createAction, handleActions} from "redux-actions";

const actions = {
	INCREASE: `${DOCUMENT}INCREASE`,
	increase: createAction(this.INCREASE),
}

최종 해결

정석
getter 함수에서 this 호출

const actions = {
  DECREASE: `${DOCUMENT}DECREASE`,
  get decrease() {
    return createAction(this.DECREASE)
  },
}

비정석
일단 함수 내부에서 this 호출.
TypeError: Cannot read property 'INCREASE' of undefined

const actions = {
  INCREASE: `${DOCUMENT}INCREASE`,
  increase: () => createAction(this.INCREASE),
}

그럼 객체 변수이름 호출.
Error: Actions must be plain objects. Use custom middleware for async actions.

increase: () => createAction(actions.INCREASE),

typeof createAction(actions.INCREASE) 하면 function.

즉시실행시켜서 객체만 리턴으로 해결

increase: () => createAction(actions.INCREASE)(),

아래와 같이 사용할 수도 있지만, :=> vs {return} 중 전자가 타이핑을 덜 치니까 개인적으로는 전자 선호.

increase() { return createAction(actions.INCREASE)()},

필요 채움: self 접근 방법

정석
this 로 접근하려면 게터, 함수 내부에서 this 사용할 것.
함수 안 쓰고 this 로 접근하면 undefined 나옴

변석
변수에 객체를 할당했다면, 객체 리터럴 내부 함수 스콥에서는 변수이름으로도 접근 가능.

가능한 이유는
1. 객체 리터럴이 별도의 스콥을 만들지 않아서 변수이름으로 접근 가능함*
2. 함수 호출 시점에서는 객체가 초기화 되어있어서 접근이 가능함
(함수 바깥에서 this 로 접근하면 undefined 나오는 것도 이 이유때문인듯?)

const someObj = {
    // 인터넷에 널린 정석
    get a() { return this.val },
    b() {return this.val},
    c: function() {return this.val},
  
    // 비정석. 객체 리터럴은 새 스콥을 만들지 않는다는 점을 이용한 객체변수 접근
    d() {return someObj.val},
    e: ()=> someObj.val,
    f: function() {return someObj.val},
   
    // 호출 시점에서 객체 초기화가 안 되어있기 때문에
    g: someObj.val, // Cannot access 'someObj' before initialization
    h: this.val, // undefined
  
    val: 'hello'
}

console.log(someObj.a)
console.log(someObj.b())
console.log(someObj.c())
console.log(someObj.d())
console.log(someObj.e())
console.log(someObj.f())
console.log(someObj.g) // Cannot access 'someObj' before initialization
console.log(someObj.h)

참조

* : https://stackoverflow.com/questions/12789141/access-object-properties-within-object

profile
다른 누구와도 같은 시장 육체 노동자

0개의 댓글