2017-09-30 1 views
0

React 구성 요소에 속성을 동적으로로드하려고합니다. 속성은 을 사용하고 async/await을 사용하여 this.props.customObjects으로 설정됩니다.React props/state와 (과) 비동기/약속을 어떻게 사용합니까?

CustomObject 구성 요소 (아래)는 약속 형태로 속성을 수신하지만 구성 요소에 실제로 가져온 데이터를 표시하는 데 실패합니다. 약속이 해결되기 전에 내 구성 요소가 렌더링되는 것 같습니다.

이 문제를 해결하는 가장 좋은 방법은 무엇입니까? async/await의 값을 props에 사용할 수 있습니까? 아니면 state을 사용해야합니까?

내 구성 요소 : 같은

export default class CustomObject extends React.Component { 

    getCustomObject = (elementType) => { 
     const customObject = this.props.customObjects[elementType]; 
     console.log('customObject', customObject); 
     return customObject; 
    } 

    componentDidMount() { 
     const customObject = this.getCustomObject(this.props.element.elementType) 
     this.setState({ customObject }); 
    } 

    render() { 
     return <div className={this.props.className} style={this.props.style}> 
      {this.state.customObject.name} // Gives TypeError: Cannot read property 'customObject' of null 
     </div> 
    } 

} 

콘솔 로그 보인다 : 당신이 말할 수있는 약속이 있다면

console.log

답변

2

뭔가 같은 :

customObject.then((result) => { 
    this.setState({customObject: result}) 
}) 

당신이있는 한 뭔가를 기다리는 중, setState을 g에 사용해야합니다. 다시 렌더링합니다. 약속이 처음 전화 할 때 render()에 계류중인 경우에 대비하여 대체해야합니다.

1

상황을 처리하는 데는 몇 가지 방법이 있습니다. 그 중 하나는 this.getCustomObject(...)이 Promise를 반환하면 해결 될 때까지 기다렸다가 상태를 설정할 수 있다는 것입니다. 약속에 대한 자세한 정보는 here를 확인하시기 바랍니다 들어

this.getCustomObject(this.props.element.elementType).then((customObject) => { 
    this.setState({ customObject }); 
}); 

예를 들어

.

this.state.customObject에 기본값을 지정하지 않으면 약속이 해결 될 때까지 정의되지 않았으므로 문제가 완전히 해결되지 않습니다. {this.state.customObject ? this.state.customObject.name : 'Loading..'}

+0

감사합니다! async/await가있을 때'then()'에 대한 대안이 있습니까? –

+0

약속을 기다리는 것이 아니라'await'을 사용할 수 있으며 동기 실행과 비슷하지만 실제로 필요하지 않는 한 제안하지 않을 것입니다. – bennygenel