2017-09-20 2 views
1

인터넷에서이 질문에 대한 답변을 검색했습니다. 찾지 못했습니다. 따라서 여기에 내 질문을 게시하고 있습니다.React - 소품이 있는지 확인하십시오.

부모 구성 요소 (App) 및 하위 구성 요소 (Child)가 있습니다. 앱 구성 요소가 너무 좋아 거기에 일부 데이터와 상태가 내 자식 구성 요소에서

class App extends Component { 
    constructor() { 
     super() 

     this.state = { 
      currentOrganization: { 
       name: 'name', 
       email: 'email' 
      } 
     } 
     render() { 
      return (
       <Child data={this.state.currentOrganization} /> 
      ) 
     } 
    } 
} 

을, 나는 양식이 다음 반작용 문서에 따르면

class Child extends Component { 
    constructor() { 
     super() 

     this.state = { 
      formData: { 
       name: '', 
       email: '', 
      } 
     } 
    } 

     render() { 
      return (
      <Form ... /> 
     ) 
     } 
    } 

를, 형태는 일반적으로해야한다 폼의 각 요소에 해당하는 속성을 포함하는 상태입니다. 내 하위 구성 요소에있는 양식에는 currentOrganization의 데이터 (App 구성 요소에 표시된대로)가 미리 채워져 있어야합니다.

이 작업을 수행하려면 하위의 상태를 부모로부터받는 소품으로 설정해야합니다.

내 자녀 구성 요소가 자신의 상태를 업데이트하기 위해 필요한 소품을 받았는지 확인하는 가장 좋은 방법은 무엇입니까?

(누구든지 알고있는 경우) React 팀이 componentDidReceiveProps()과 같은 라이프 사이클 기능을 추가하지 않은 이유는 무엇입니까?

+3

? "팀에서() componentDidReceiveProps 같은 라이프 사이클 기능을 추가하지 않은 반작용 이유는 무엇인가"와 같은 속성을 확인 할 수 있습니다 props은 JS 객체입니다 당신? https://facebook.github.io/react/docs/react-component.html#componentwillreceiveprops –

+0

React have have'componentWillReceiveProps' –

+0

무엇을 위해서입니까? 제 말은 여러분이 구성 요소가 실제로 필요한 것 대신 전체 상태를 통과하는 것입니다 - 여러분은 건설, didMount, willReceiveProps 등에서 소품을 점검해야합니다. 나는 그 질문을 이해하지 못합니다. –

답변

6

초기 소품을 constructor에서 확인할 수 있습니다.

class Child extends Component { 
    constructor(props) { 
    super(props); 

    this.state = { 
     formData: { 
     name: props.name || '', 
     email: props.email || '', 
     } 
    } 
    } 

    render() { 
    return (
     <Form ... /> 
    ) 
    } 
} 

P. >합니까`componentWillReceiveProps()`작동하지 -이 "prop_name" in this.props // true|false

+0

+1 'this.props' 대신 생성자에서'props.xxx'를 사용하고 null 대신 입력 값에 빈 문자열을 사용하는 경우 +1. – Chris

+0

다음과 같이 작성할 수도 있습니다 :'const {name = '', email = ''} = props' 그리고 * this.state.formData ({name, email})'* constructor *. – zvona

+0

'this.state.formData()'? –

관련 문제