반응형
컴포넌트의 Reactjs 비동기 렌더링
내 ajax 요청이 완료된 후 구성 요소를 렌더링하고 싶습니다.
아래에서 내 코드를 볼 수 있습니다.
var CategoriesSetup = React.createClass({
render: function(){
var rows = [];
$.get('http://foobar.io/api/v1/listings/categories/').done(function (data) {
$.each(data, function(index, element){
rows.push(<OptionRow obj={element} />);
});
return (<Input type='select'>{rows}</Input>)
})
}
});
하지만 내 ajax 요청의 done 메서드 내에서 렌더링을 반환하기 때문에 아래 오류가 발생합니다.
Uncaught Error: Invariant Violation: CategoriesSetup.render(): A valid ReactComponent must be returned. You may have returned undefined, an array or some other invalid object.
렌더링을 시작하기 전에 내 ajax 요청이 끝날 때까지 기다리는 방법이 있습니까?
이를 처리하는 방법에는 두 가지가 있으며, 데이터를 소유해야하는 구성 요소와로드 상태에 따라 선택하는 방법이 다릅니다.
Ajax 요청을 부모로 이동하고 구성 요소를 조건부로 렌더링합니다.
var Parent = React.createClass({ getInitialState: function() { return { data: null }; }, componentDidMount: function() { $.get('http://foobar.io/api/v1/listings/categories/').done(function(data) { this.setState({data: data}); }.bind(this)); }, render: function() { if (this.state.data) { return <CategoriesSetup data={this.state.data} />; } return <div>Loading...</div>; } });
Ajax 요청을 구성 요소에 유지하고로드하는 동안 조건부로 다른 것을 렌더링합니다.
var CategoriesSetup = React.createClass({ getInitialState: function() { return { data: null }; }, componentDidMount: function() { $.get('http://foobar.io/api/v1/listings/categories/').done(function(data) { this.setState({data: data}); }.bind(this)); }, render: function() { if (this.state.data) { return <Input type="select">{this.state.data.map(this.renderRow)}</Input>; } return <div>Loading...</div>; }, renderRow: function(row) { return <OptionRow obj={row} />; } });
구성 요소의 비동기 렌더링의 기본 예는 다음과 같습니다.
import React from 'react';
import ReactDOM from 'react-dom';
import PropTypes from 'prop-types';
export default class YourComponent extends React.PureComponent {
constructor(props){
super(props);
this.state = {
data: null
}
}
componentDidMount(){
const data = {
optPost: 'userToStat01',
message: 'We make a research of fetch'
};
const endpoint = 'http://example.com/api/phpGetPost.php';
const setState = this.setState.bind(this);
fetch(endpoint, {
method: 'POST',
body: JSON.stringify(data)
})
.then((resp) => resp.json())
.then(function(response) {
setState({data: response.message});
});
}
render(){
return (<div>
{this.state.data === null ?
<div>Loading</div>
:
<div>{this.state.data}</div>
}
</div>);
}
}
참고 URL : https://stackoverflow.com/questions/27192621/reactjs-async-rendering-of-components
반응형
'IT TIP' 카테고리의 다른 글
OpenGraph 또는 Schema.org? (0) | 2020.10.16 |
---|---|
OWIN 보안-OAuth2 새로 고침 토큰 구현 방법 (0) | 2020.10.16 |
Android 스튜디오 gradle.properties 파일은 어디에 있습니까? (0) | 2020.10.16 |
Visual Studio 2017에서 Microsoft.NETCore.App 패키지를 업데이트 할 수 없습니다 ( "프로젝트에서 차단됨"). (0) | 2020.10.16 |
파일 다운로드를 추적하는 방법 (0) | 2020.10.16 |