Computer >> 컴퓨터 >  >> 프로그램 작성 >> JavaScript

React Native에서 서버에서 데이터를 로드하는 방법은 무엇입니까?

<시간/>

서버에서 데이터를 로드하려면 fetch API를 사용할 수 있습니다. XMLHttpRequest와 유사합니다. 또는 기타 네트워킹 API.

fetch를 사용하여 서버에 요청하는 것은 매우 쉽습니다. 다음 코드를 살펴보십시오 -

fetch('https://jsonplaceholder.typicode.com/posts/1') .then((response) => response.json()) .then((responseJson) => console.log(responseJson));

위의 코드에서 JSON 파일 https://jsonplaceholder.typicode.com/posts/1을 가져오고 데이터를 콘솔에 인쇄합니다. fetch() API에 대한 가장 간단한 호출은 하나의 인수, 즉 가져오려는 경로를 취하고 응답과 함께 약속을 반환합니다.

fetch API는 json() 메서드를 사용하는 데 필요한 응답에서 JSON 본문을 가져오기 위해 http 응답과 함께 약속을 반환합니다.

가져오기 API의 두 번째 매개변수는 (GET, POST) 메서드, 헤더, 게시하려는 데이터 등을 가질 수 있는 개체입니다.

다음은 서버에서 데이터를 가져와 사용자에게 표시하는 방법을 보여주는 실제 예입니다.

예:가져오기 API를 사용하여 데이터 가져오기

데이터는 아래와 같이 시작 시 비어 있도록 초기화됩니다. -

상태 ={ 데이터:''}

componentDidMount()에 대한 세부 정보

fetch API는 componentDidMount() 함수 내에서 호출됩니다. componentDidMount()는 구성 요소가 마운트된 직후, 즉 모든 요소가 페이지에 렌더링된 직후에 호출됩니다.

다음은 동일한 코드입니다 -

componentDidMount =() => { fetch('https://jsonplaceholder.typicode.com/posts/1', { 메서드:'GET' }) .then((response) => response.json()) .then((responseJson) => { console.log(responseJson); this.setState({ 데이터:responseJson }) }) .catch((오류) => { console.error(오류); });} 

url :https://jsonplaceholder.typicode.com/posts/1의 데이터는 다음과 같습니다 -

{ "userId":1, "id":1, "title":"sunt aut facere repellat Provident occaecati excepturi optio reprehenderit", "body":"quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nstrum rerum est autem sunt rem Eveniet architecture"}

본문 안에 텍스트를 표시하는 데 관심이 있습니다.

데이터 변수는 아래와 같이 setState 메소드를 사용하여 업데이트됩니다. -

this.setState({ 데이터:responseJson})

이제 this.state.data.body에는 아래와 같이 사용자에게 표시하는 데 사용할 수 있는 서버의 데이터가 있습니다. -

render() { return (   {this.state.data.body}   )}

다음은 fetch Api를 사용하여 서버에서 데이터를 가져오는 작업 코드입니다 -

"react"에서 React, { Component } 가져오기; "react-native"에서 { Text, View } 가져오기;class HttpExample extends Component { state ={ data:'' } componentDidMount =() => { fetch(' https://jsonplaceholder.typicode.com/posts/1', { 메소드:'GET' }) .then((response) => response.json()) .then((responseJson) => { console.log( responseJson); this.setState({ 데이터:responseJson }) }) .catch((error) => { console.error(error); });}render() { return (   {this. state.data.body}   ) }}const App =() => { return (  )}기본 앱 내보내기

출력

React Native에서 서버에서 데이터를 로드하는 방법은 무엇입니까?