[英]React Native - FlatList make get request for each item in renderItems
我想对我的renderItems()
每个项目进行get
请求,因此我将其设置为:
renderItems({ item }) {
axios.get(Utilities.url + "Symbol/" + item.Id).then(response => {
let eachItem = response.data;
});
console.log(eachItem);
return (
<View
style={{
flex: 1,
justifyContent: "center",
alignItems: "flex-end",
alignSelf: "stretch",
marginRight: 2
}}
>
<Text
style={{
color: Colors.WHITE,
fontSize: 16
}}
>
{eachItem.LVal18AFC}
</Text>
</View>
);
}
但是我得到以下错误:
ReferenceError:每个项目未定义
我试图将renderItems
转换为async
函数并使用await
但出现另一个错误!
任何解决方案...?
我在axios的then函数之外使用了var eachItem = []
,但是现在我得到了:
TypeError:无法读取未定义的属性“ LVal18AFC”!
@Jigar是正确的。 为何不起作用:当您调用renderItems
函数时,js会查看asyn调用,并将其放入其事件循环中,以便以后执行。 然后,它继续运行并将当前未定义的eachItem
记录到控制台。 然后呈现您的JSX,然后在要求供应将数据备份的目的只是为了存储执行异步调用(即Axios公司要求) eachItem
这是在爱可信功能的范围。
您在调用API时做了一个不好的做法,我的建议是,为要显示的每一行创建一个单独的组件,并在行内调用所需的API
所以根据你的代码
class Row extends Component {
constructor() {
super()
this.state = {
eachItem: null
}
}
componentDidMount() {
const { item } = this.props;
axios.get(Utilities.url + "Symbol/" + item.Id).then(response => {
this.setState({eachItem: response.data});
});
}
render() {
return (
<View
style={{
flex: 1,
justifyContent: "center",
alignItems: "flex-end",
alignSelf: "stretch",
marginRight: 2
}}
>
<Text
style={{
color: Colors.WHITE,
fontSize: 16
}}
>
{this.state.eachItem ? this.state.eachItem.LVal18AFC : null}
</Text>
</View>
);
}
}
这是一个范围界定问题。 在传递给GET
promise的函数中使用let
关键字,意味着只能在该函数内部访问它。
我实际上建议将事物抽象到一个组件中,该组件将管理其自己的axios调用。 像这样:
class Item {
componentWillMount(props) {
axios.get(Utilities.url + "Symbol/" + props.Id).then(response => {
this.setState({
data: {
...this.state.data,
...response.data,
})
});
}
render() {
if (!this.state.data) {
return null;
}
return (
<View
style={{
flex: 1,
justifyContent: "center",
alignItems: "flex-end",
alignSelf: "stretch",
marginRight: 2
}}
>
<Text
style={{
color: Colors.WHITE,
fontSize: 16
}}
>
{ this.state.data.id }
</Text>
</View>
);
}
}
function Parent(props) {
<FlatList renderItem={ ({ item }) => <Item id={ item.id } /> } />
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.