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>
}
}
콘솔 로그 보인다 : 당신이 말할 수있는 약속이 있다면
감사합니다! async/await가있을 때'then()'에 대한 대안이 있습니까? –
약속을 기다리는 것이 아니라'await'을 사용할 수 있으며 동기 실행과 비슷하지만 실제로 필요하지 않는 한 제안하지 않을 것입니다. – bennygenel