屏幕上未显示任何内容。不知道为什么会这样,任何地方都没有错误。想知道为什么屏幕上什么都没有显示。从API中正确获取数据。代码如下:
import React, { Component } from 'react';
import { StyleSheet, ScrollView, TouchableOpacity, Text, View } from 'react-native';
import { Container, Content, Grid, Row, Col } from 'native-base';
import axios from 'axios';
import ItemCard from '../components/ItemCard';
export default class ItemHorizontalScreen extends Component {
constructor(props) {
super(props)
this.state = {
items: []
}
}
componentWillMount() {
axios.get('http://rallycoding.herokuapp.com/api/music_albums').then(response =>
this.setState({
items: response.data
}))
.catch((error) => {
console.error(error);
})
}
renderHorizontalContents() {
const rowItems = this.state.items
rowItems.map((rowItem, index) => {
return (
<TouchableOpacity key={index}>
<Text>{rowItem.title}</Text>
</TouchableOpacity>
)
})
}
render() {
return (
<View>
{this.renderHorizontalContents()}
</View>
)
}
}发布于 2018-10-16 21:39:04
您的renderHorizontalContents()应返回以下列表:
renderHorizontalContents() {
const rowItems = this.state.items
return rowItems.map((rowItem, index) => {
return (
<TouchableOpacity key={index}>
<Text>{rowItem.title}</Text>
</TouchableOpacity>
)
})
} 另外,半相关的,从React 16.3React团队建议不要使用componentWillMount()。您应该在componentDidMount() LifeCycle钩子中获取数据。
有关componentWillMount()弃用的更多信息:
https://github.com/styled-components/styled-components/issues/1575
发布于 2018-10-16 21:39:36
尝尝这个。问题是renderHorizontalContents()没有返回,所以您必须返回映射为您返回的元素
另外,关于添加key,如果items数组包含每个对象的唯一id,那么建议使用它作为key。如果数据中没有唯一的id,那么索引始终是第二个选择。另外,当添加索引作为键时,你应该像我在下面做的那样添加一些东西,而不是直接添加索引作为键。
renderHorizontalContents() {
const { items } = this.state;
return items.map((rowItem, index) => {
return (
<TouchableOpacity key={"Key"+index}>
<Text>{rowItem.title}</Text>
</TouchableOpacity>
)
})
} https://stackoverflow.com/questions/52836767
复制相似问题