[React Native] サーバーやDBからのデータ取得
6613 ワード
0. 目的
Hooksを用いてサーバーやDBからデータを取得
1. 環境
- React : 16.8.6
- React Native : 0.63.4
2. ソースコード
GetData.js
import React from 'react';
import {FlatList, Text, View} from 'react-native';
import {useEffect, useState} from 'react';
function App() {
const [response, setResponse] = useState([]);
useEffect(() => {
// データ取得(DBの場合もここでread処理を行う)
fetch('https://zipcloud.ibsnet.co.jp/api/search?zipcode=7830060') // [1]
.then((response) => response.json())
.then((responseJson) => {
setResponse(responseJson['results']);
});
}, []);
if (!response.length) { // データ取得前
return <Text>Loading...</Text>;
} else if (response.length) { // データ取得後
return (
<FlatList
data={response}
renderItem={({item}) => (
<View>
<Text>〒{item.zipcode}</Text>
<Text>
{item.address1}
{item.address2}
{item.address3}
</Text>
</View>
)}
keyExtractor={(item) => item.zipcode}
/>
);
}
}
export default App;
3. 結果
GetData.js
import React from 'react';
import {FlatList, Text, View} from 'react-native';
import {useEffect, useState} from 'react';
function App() {
const [response, setResponse] = useState([]);
useEffect(() => {
// データ取得(DBの場合もここでread処理を行う)
fetch('https://zipcloud.ibsnet.co.jp/api/search?zipcode=7830060') // [1]
.then((response) => response.json())
.then((responseJson) => {
setResponse(responseJson['results']);
});
}, []);
if (!response.length) { // データ取得前
return <Text>Loading...</Text>;
} else if (response.length) { // データ取得後
return (
<FlatList
data={response}
renderItem={({item}) => (
<View>
<Text>〒{item.zipcode}</Text>
<Text>
{item.address1}
{item.address2}
{item.address3}
</Text>
</View>
)}
keyExtractor={(item) => item.zipcode}
/>
);
}
}
export default App;
3. 結果
「Loading」が表示された後、上の画像のように描画される.
4. 解説
処理の流れ
1. 「Loading」を表示
2. 「useEffect」内の処理を実行
3. 「住所」を表示
useEffectはレンダリング後に実行されるため、responseの有無により描画内容を変更する.
また、setResponseによりresponseの値が変更された際に再レンダリングされるため、データ取得後には再度if文が実行され、データ内容が表示される.
5. 参考
[1]郵便番号検索API
Author And Source
この問題について([React Native] サーバーやDBからのデータ取得), 我々は、より多くの情報をここで見つけました https://qiita.com/nram/items/3d2f58a2a4f4bf610b40著者帰属:元の著者の情報は、元のURLに含まれています。著作権は原作者に属する。
Content is automatically searched and collected through network algorithms . If there is a violation . Please contact us . We will adjust (correct author information ,or delete content ) as soon as possible .