api - 如何在获取成功响应中呈现 react-native 组件?
问题描述
我正在尝试显示带有每种属性类型的属性数量的徽章。接收到来自 API 的数据,但 Badge 组件不呈现。
countProp = (id) => {
fetch('http://10.0.2.2:8000/api/property/' + id).then((data) => data.json())
.then((response) => {
```return <Badge value={response.properties.length}/>
});
};
此后,在此renderItem
方法中调用以下函数,该函数用作数组迭代器来呈现属性类型:
renderItem = ({item}) => {
return(
<View>
....
```{this.countProp(item.id)}
</View>
)
}
解决方案
您可能会发现将其分解为单独的组件并在 componentDidMount 中进行 api 调用更容易,例如:
import React, { Component } from "react";
import { Text, View } from "react-native";
export default class Item extends Component {
componentDidMount() {
fetch("http://10.0.2.2:8000/api/property/" + this.props.id)
.then(data => data.json())
.then(response => {
this.setState({ length: response.properties.length });
});
}
render() {
if (!this.state.length) {
return null;
}
return (
<View>
<Badge value={this.state.length} />
</View>
);
}
}
然后使用这个组件传递它的 id:
import Item from "./path/to/Item.js";
...
<Item id={ 7 } />
推荐阅读
- javascript - 如何使用 DOM 操作动态创建模板元素
- clion - 如何使用自定义参数在 CLion 上运行 OpenOCD?
- c - glibc 中以 __NR_ 为前缀的符号是什么?
- html - 背景图像被裁剪而不是适合移动设备上的元素
- python - 使局部变量成为全局变量
- sql - PostgreSQL。查找最近的字符串模式匹配
- javascript - 我可以从 HTTP GET 请求 URL 中请求的 html 中获取参数吗?
- python - Python - 用渐进式数字替换日期列
- php - php 数组根据父数组用 '0' 填充一个虚拟值
- php - 在 WooCommerce 中 72 小时后清空用户的购物车而不将其注销