2017-04-25 1 views
1

그래서, 내 구성 요소는 상위 구성 요소에서 개체를 수신 객체가이 모양 렌더링 :ReactJS는 : 배열에 객체를 켜고

내 아이 구성 요소에서
{ 
    _id: Data.now(), // MongoDB database 
    name: "", 
    description: "", 
    image: "images/image.jpg", 
    type: "image" 
} 

, 나는이 데이터를 받아와를 만들고 싶어 각 하나에 대한 입력 값을 변경하고 새 데이터를 저장할 수 있습니다.

업데이트 응답 (ES6 클래스) :

constructor(props) { 
    super(); 
    this.state = { 
    fieldGroups: [] 
    } 

    this.parseProps = this.parseProps.bind(this); 
} 

componentWillMount() { 
    this.parseProps(this.props); 
} 

componentWillReceiveProps(nextProps) { 
    this.parseProps(nextProps); 
} 

parseProps(props) { 
    var fieldsArray = []; 
    var content = props.content; 
    Object.keys(content).map((field,index) => { 
    if (field === 'type') { 
     let fieldObj = {}; 
     fieldObj.field = field; 
     fieldObj.value = content[field]; 
     fieldObj.key = props.content._id + field; 
     fieldsArray.push(fieldObj); 
    } 
    }); 
    this.setState({ 
    fieldGroups: fieldsArray 
    }); 
} 

render() { 
    return (
    { 
     this.state.fieldGroups.map((field) => { 
     if (field.field === "type") { 
     return (html element specific to type) 
     } else { 
     return (a different html element) 
     } 
    }) 
    } 
) 
} 

그래서 지금은 아이 컴포넌트는 사용자를 보여 필드 결정 댄다는 의미에서 내 구성 요소를 분리 할 수 ​​있습니다. 감사합니다 DanneManne

+0

불완전한 예를 들어 설명하기가 어렵습니다. 이 구성 요소에 대해 더 많은 코드를 표시 할 수 있습니까? 수업입니까? 생성자를 올바르게 구현 했습니까? https://stackoverflow.com/help/mcve –

답변

1

기능이 componentDidMount은 명명 된 것과 마찬가지로 구성 요소가 마운트 된 후에 한 번만 호출됩니다. 그러나 부모 구성 요소가 업데이트 된 속성으로 자식 구성 요소를 다시 렌더링하는 경우 자식은 이미 탑재되어 있으며 해당 함수는 다시 호출되지 않습니다.

주목해야 할 또 다른 점은 componentDidMount의 목적은 당신이 offsetWidth 또는 다른 요소의 offsetHeight 같은 것들을보고 싶을 경우 실제 DOM에서 데이터를 가져올 수 있다는 것입니다,하지만 당신은 전혀 DOM을 사용하지 않는 경우, DOM을 추가로 조작하지 않으려면 componentWillMount을 사용하는 것이 좋습니다. 일반적으로 DOM은 시간이 가장 많이 걸리는 부분이므로 DOM을 추가로 조작하지 않아야합니다.

누락 된 부분은 componentWillReceiveProps과 함께 componentWillMount의 결합 된 사용법입니다. 이는 부모가 자식을 다시 렌더링 할 때마다 호출되는 함수입니다.

나는 보통으로 이동 패턴은 다음과 같습니다

constructor(props){ 
    super(); 
    this.parseProps = this.parseProps.bind(this); 
    } 

    componentWillMount() { 
    this.parseProps(this.props); 
    } 

    componentWillReceiveProps(nextProps) { 
    this.parseProps(nextProps); 
    } 

    // === Parsing Props 
    // 
    // Takes care of component specific adjustment of 
    // props that parent components does not need to 
    // know about. An example can be sorting or grouping 
    // of records. 
    // 
    parseProps(props) { 
    this.setState({ 
     // key: props.key 
    }); 
    } 

그래서 현재 componentDidMount에서이 논리는 parseProps 함수로 이동할 수 있습니다.

+0

이봐, 제대로 작동 했어. 해결책이 약간의 재판을 받았기 때문에 대답을 업데이트 할 것이다. 또한 불필요하게 물건을 추가 할 수도 있습니다. – Daltron