2017-12-10 17 views
1

내가 이런 식으로 할 수있는 방법이 있습니까?if 구문 내에서 어쨌든 destructuring을 사용할 수 있습니까?

if({color, size, shape} = this.props){ 
    console.log('Received all props!'); 
} else { 
    console.log('There are some missing props'); 
} 

나는 내 구성 요소의 소품, 을 통해 다음 오류가 발생하지 않을 경우 필요한 모든 데이터를받은 경우 알고 싶어요.

재사용 가능한 구성 요소를 만드는 데 사용됩니다.

+0

그것은 구문 적으로 유효한 (또는 더 나은 아직, 예상 값의 종류를 확인), 그러나 당신이하고 싶은 일을하지 않습니다. – Bergi

+0

당신은 그 같은 여러 속성의 진실성을 확인할 수 없습니다 –

+1

만약 당신이 전에 방금 소품을 추출하고 일반 vars처럼 그들을 확인하지? 나는 제안 된 방법을 사용하여 무엇을 얻을 것인가가 보이지 않는다. ... – Coluccini

답변

4

당신은 기본값을 사용할 수 있습니다

function missing(prop) { 
    throw new TypeError(`there is a missing ${prop} property`); 
} 

… 
try { 
    const { 
    color = missing("color"), 
    size = missing("size"), 
    shape = missing("shape"), 
    } = this.props; 
    // use color, size, shape here 
    console.log("Received all props!"); 
} catch(err) { 
    console.log(err.message); 
} 

if 문을 사용하려면, 아니 당신은 모든 속성이 있는지 여부를 부울을 생산하는 destructuring을 사용할 수 없습니다. 오히려

if ("color" in this.props && "size" in this.props && "shape" in this.props) { 
    console.log('Received all props!'); 
} else { 
    console.log('There are some missing props'); 
} 

평소처럼 뭔가 할