【发布时间】:2020-11-12 08:26:21
【问题描述】:
所以我收到了这样一个 API 的响应, 如何从 API 逆向检查空对象? 我曾尝试使用 lodash 来检查它,但这在 react native 中效果不佳,我没有进一步研究它
这是我的状态
const [product, setProduct] = useState([])
const [loading, setLoading] = useState(true)
const getProduct = () => {
api.get(`/v1/snack/product/nearby?idKecamatan=${dataKecamatan.idKecamatan}`,
{ headers: { 'Authorization': 'Bearer' + AsyncStorage.getItem('app-token') } }
)
.then(res => {
setProduct(res.data)
setLoading(!loading)
console.log(res.data)
})
}
useEffect(() => {
navigation.addListener('focus', () => {
getProduct()
})
}, [navigation])
<View>
{Object.keys(product.Data).length === 0 ? (
<Text>data from 'Data' is empty</Text>
) : (
<View>
<Text>Data not empty</Text>
</View>
)}
</View>
如果数据不为空
{
"Data": {
"data": [
{
"idSnack": 1,
"codeSnack": "MCA69825829",
"nameSnack": "Taro",
"imageSnack": "localhost/snack-upload/public/media/product/130720xMDVDa_8hrNIx.jpg",
"price": "16500.00",
"rating": 0,
"productSold": 0,
"favStatus": 1,
"idAgen": 2
}
],
"metadata": {
"total": 2,
"count": 2,
"per_page": 20,
"current_page": 1,
"total_pages": 1,
"prev_page": "",
"next_page": ""
}
},
"Message": "SUCCESS"
}
如果数据为空,则响应如下:
{
"Data": {},
"Message": "Tidak ada snack disekitarmu"
}
如果数据为空,我希望这样返回
<View>
{Object.keys(product.Data).length === 0 ? (
<Text>gk ada</Text>
) : (
<View>
<Text>ada</Text>
</View>
)}
</View>
【问题讨论】:
-
那么问题是什么?
-
您没有显示上一次 sn-p 中
Data的定义位置。 -
如果我不能条件 if Data: {} if Data: {} 应该进入 console.log ('data is empty')
-
您可以在这里得到答案:stackoverflow.com/questions/679915/…
-
我试过了,但不适合我,我不明白
标签: javascript reactjs object