렌더링하기 전에 서버에서 데이터 가져오기 응답
나는 리액션을 처음 해, 서버에 데이터를 가져와 클라이언트에게 데이터가 포함된 페이지를 보내고 싶어.
함수 getDefaultProps가 {data: {books: [{..}, {..}과 같은 더미 데이터를 반환할 때 괜찮다.}]}}.
그러나 아래 코드에서는 작동하지 마십시오."정의되지 않은 속성 '책'을 읽을 수 없음" 오류 메시지와 함께 이 순서로 코드가 실행됨
- getDefaultProps
- 돌아오다
- 을 가져오다
- {data: {books: [{..}, {..}}]}}
하지만, 나는 코드가 이 순서대로 실행되어야 한다고 생각한다.
- getDefaultProps
- 을 가져오다
- {data: {books: [{..}, {..}}]}}
- 돌아오다
감 잡히는 게 없어요?
statics: {
fetchData: function(callback) {
var me = this;
superagent.get('http://localhost:3100/api/books')
.accept('json')
.end(function(err, res){
if (err) throw err;
var data = {data: {books: res.body} }
console.log('fetch');
callback(data);
});
}
getDefaultProps: function() {
console.log('getDefaultProps');
var me = this;
me.data = '';
this.fetchData(function(data){
console.log('callback');
console.log(data);
me.data = data;
});
console.log('return');
return me.data;
},
render: function() {
console.log('render book-list');
return (
<div>
<ul>
{
this.props.data.books.map(function(book) {
return <li key={book.name}>{book.name}</li>
})
}
</ul>
</div>
);
}
네가 찾는 건componentWillMount
.
설명서:
초기 렌더링이 발생하기 직전에 클라이언트와 서버에서 모두 한 번 호출됨.전화하면
setState
이 방법으로render()
업데이트된 상태를 확인하고 상태 변경에도 불구하고 한 번만 실행된다.
그래서 당신은 이런 일을 할 것이다.
componentWillMount : function () {
var data = this.getData();
this.setState({data : data});
},
이쪽입니다.render()
한 번만 호출하면 초기 렌더링에서 원하는 데이터를 얻을 수 있을 겁니다.
이것의 아주 간단한 예.
import React, { Component } from 'react';
import { View, Text } from 'react-native';
export default class App extends React.Component {
constructor(props) {
super(props);
this.state = {
data : null
};
}
componentWillMount() {
this.renderMyData();
}
renderMyData(){
fetch('https://your url')
.then((response) => response.json())
.then((responseJson) => {
this.setState({ data : responseJson })
})
.catch((error) => {
console.error(error);
});
}
render(){
return(
<View>
{this.state.data ? <MyComponent data={this.state.data} /> : <MyLoadingComponnents /> }
</View>
);
}
}
서버에서 데이터를 수신하여 표시하는 데 사용하는 최상의 답변
constructor(props){
super(props);
this.state = {
items2 : [{}],
isLoading: true
}
}
componentWillMount (){
axios({
method: 'get',
responseType: 'json',
url: '....',
})
.then(response => {
self.setState({
items2: response ,
isLoading: false
});
console.log("Asmaa Almadhoun *** : " + self.state.items2);
})
.catch(error => {
console.log("Error *** : " + error);
});
})}
render() {
return(
{ this.state.isLoading &&
<i className="fa fa-spinner fa-spin"></i>
}
{ !this.state.isLoading &&
//external component passing Server data to its classes
<TestDynamic items={this.state.items2}/>
}
) }
인 리액션,props
데이터 취급이 아닌 구성요소 매개변수에 사용된다.라고 하는 것에 대한 별도의 구문이 있다.state
. 업데이트할 때마다state
구성요소는 기본적으로 새로운 값에 따라 자체 렌더링된다.
var BookList = React.createClass({
// Fetches the book list from the server
getBookList: function() {
superagent.get('http://localhost:3100/api/books')
.accept('json')
.end(function(err, res) {
if (err) throw err;
this.setBookListState(res);
});
},
// Custom function we'll use to update the component state
setBookListState: function(books) {
this.setState({
books: books.data
});
},
// React exposes this function to allow you to set the default state
// of your component
getInitialState: function() {
return {
books: []
};
},
// React exposes this function, which you can think of as the
// constructor of your component. Call for your data here.
componentDidMount: function() {
this.getBookList();
},
render: function() {
var books = this.state.books.map(function(book) {
return (
<li key={book.key}>{book.name}</li>
);
});
return (
<div>
<ul>
{books}
</ul>
</div>
);
}
});
Michael Parker의 답변의 보충 자료로 getData가 콜백 함수를 수락하여 setState update data를 활성화하도록 할 수 있다.
componentWillMount : function () {
var data = this.getData(()=>this.setState({data : data}));
},
나도 리액션을 배우면서 우연히 이 문제를 발견했고, 데이터가 준비될 때까지 스피너를 보여줌으로써 해결했다.
render() {
if (this.state.data === null) {
return (
<div className="MyView">
<Spinner/>
</div>
);
}
else {
return(
<div className="MyView">
<ReactJson src={this.state.data}/>
</div>
);
}
}
이와 유사한 질문에 대답할 수 있는 간단한 해결책이 제시된 경우, 다음과 같은 질문에 답할 수 있다. 즉, 환원 사가스 사용과 관련이 있다는 점이다.
https://stackoverflow.com/a/38701184/978306
아니면 내가 그 주제에 대해 쓴 기사로 바로 넘어가라.
https://medium.com/@f77ab66900a/dv-server-side-with-remensx-store-hydration-9f77ab66900a
렌더링을 시도하기 전에 서버에서 데이터를 프리페치하는 데 재다이얼 패키지를 사용할 수 있음
사용 시도componentDidMount
:
componentDidMount : function () {
// Your code goes here
},
자세한 내용은 여기를 참조하십시오.
후크를 사용하는 경우useEffect
스위치:
useEffect(() => {
// Your code goes here
});
문서화:useEffect
참조URL: https://stackoverflow.com/questions/30929679/react-fetch-data-in-server-before-render
'Programing' 카테고리의 다른 글
Zip in reactive 기본 프로젝트를 확장할 수 없음 (0) | 2022.03.12 |
---|---|
라우터 링크와 vue 및 vuetify 혼동 (0) | 2022.03.12 |
"유니코드 오류 "유니코드 이스케이프" 코덱이 바이트를 디코딩할 수 없음...Python 3에서 텍스트 파일을 열 수 없음 (0) | 2022.03.12 |
vs 코드를 사용하여 Vuejs 애플리케이션 실행 (0) | 2022.03.12 |
Vuex + VueJS: 계산된 속성을 하위 항목에 전달하는 것은 정의되지 않음 (0) | 2022.03.12 |