使用React native和Axios从数据库获取数据



我试图从API获取数据在我的本地主机服务器使用"Axios"在React Native中,但是数据没有从API中获取,也没有显示。如果你问的是http请求在服务器端工作,是的,这是工作。任何评论和想法都将非常感谢:)

http.common:

export default axios.create({
baseURL: "http://localhost:19002/api",
headers: {
"Content-type": "application/json",
"Access-Control-Allow-Origin" : "*",
"Access-Control-Allow-Methods": "GET,PUT,POST,PATCH,DELETE",
"Access-Control-Allow-Headers": "Origin, X-Requested-With, Content-Type, Accept"
}
});

Card.js:

import dataAPI from '../http/http.common'

function Card() {

const [items, setItems] = useState([]);
useEffect(() => {
getDataFromAPI()
}, [])

function getDataFromAPI() {
dataAPI.get('/latest')
.then(async function (response) {
setItems(response.data);
})
.catch(function (error) {
console.log(error)
})
}
if (!items) {
return null
}
return (
<FlatGrid
itemDimension={130}
data={items}
style={styles.gridView}

spacing={10}
keyExtractor={(item, index) => 'key' + index}
renderItem={({ item }) => (
<TextCard item= {item} />
)}
/>

);
}

TextCard.js

const TextCard = ({item }) => {
console.log(item)
return (
<>
<View style={[styles.itemContainer, { backgroundColor: '#fff' }]}>
<Image style={styles.itemImg} source={require('../assets/temperature.png')} />
<Text style={styles.itemName}>Température</Text>
<Text style={styles.itemCode}>{item.Temperature} </Text>

</View>



</>
)
}

尝试将extraData={{length: items.length}}作为道具传递给FlatList

并且为了确保状态被更新,将以下钩子添加到Card组件

useEffect(() => {
console.log(`There are ${items.length} items in the state right now`)
}, [items.length])

让我知道它是否解决了,如果没有,我将不得不重复这个问题,看看它是从哪里来的