2016-08-30 3 views
0

아래 코드가 { active, children, onClick }의 관점에서 어떻게 작동하는지 파악하려고합니다. 여기서 중괄호는 무엇입니까? 나는 const Link = (props) => 대신 props.active 등을 사용하여 함수에서 값에 접근 할 것을 기대했을 것입니다. 이것은 아래의 내 CommentBox 예제에서 제가하고있는 것입니다.순수 함수의 중괄호 사용

링크 :

import React, { PropTypes } from 'react' 

const Link = ({ active, children, onClick }) => { 
    if (active) { 
    return <span>{children}</span> 
    } 

    return (
    <a href="#" 
     onClick={e => { 
     e.preventDefault() 
     onClick() 
     }} 
    > 
     {children} 
    </a> 
) 
} 

FilterLink :

import { connect } from 'react-redux' 
import { setVisibilityFilter } from '../actions' 
import Link from '../components/Link' 

const mapStateToProps = (state, ownProps) => { 
    return { 
    active: ownProps.filter === state.visibilityFilter 
    } 
} 

const mapDispatchToProps = (dispatch, ownProps) => { 
    return { 
    onClick:() => { 
     dispatch(setVisibilityFilter(ownProps.filter)) 
    } 
    } 
} 

const FilterLink = connect(
    mapStateToProps, 
    mapDispatchToProps 
)(Link) 

export default FilterLink 

http://redux.js.org/docs/basics/ExampleTodoList.html

CommentBox :

const CommentBox = (props) => 
     <div className="commentBox"> 
     <h1>Comments</h1> 
     { props.comments.valueSeq().map((comment) => 
       <Comment author={comment.author} key={comment.id}> 
       {comment.text} 
       </Comment> 
       )} 

     <CommentForm /> 
     </div> 

function mapStateToProps(state) { 
    return {comments: state.get('comments')}; 
} 
+2

'링크 = ({활성, 어린이, 온 클릭}) => {...'하고 링크 = (소품)'과 동일 => {var에 활성 = props.active, 어린이 = props.children , onClick = props.onClick; ...}'- 불리는 ** destructuring **. –

답변

3
const Link = ({ active, children, onClick }) => { ... }); 

이 작업은 첫 번째 인수를 소멸시키는 것입니다. 첫 번째 인수가 적어도 active, childrenonClick 속성을 가진 객체라고 가정하면이 객체는 동일한 이름의 변수에 직접 매핑됩니다.

조치 here에서 확인할 수 있습니다.

// ES6 
function foo({bar, baz}, bam){ 
    console.log(bar, baz) 
} 

// ES5 
"use strict"; 

function foo(_ref, bam) { 
    var bar = _ref.bar; 
    var baz = _ref.baz; 

    console.log(bar, baz, bam); 
} 
+0

이 페이지는 좋은 예제를 제공한다고 생각합니다. http://www.jstips.co/en/use-destructuring-in-function-parameters/ – Giuseppe

관련 문제