我只是一个初学者,并一直在工作的项目,需要尽快完成。我已经通过API获取了5000多个数据列表,但是,该列表在滚动时效率低下,因此破坏了应用程序。我一直在React Native中寻找无法在我的项目上正确实现的React Native组件。有谁能就如何解决这个问题提出建议吗?我已将我的源代码附在下面-
import React, {Component} from 'react';
import {Text, View, FlatList, ScrollView } from 'react-native';
import axios from 'axios';
import GalleryDetail from './GalleryDetail';
class GalleryList extends Component {
state = { photos: []};
componentWillMount() {
axios.get('http://jsonplaceholder.typicode.com/photos')
.then(response => this.setState({ photos: response.data })).
catch((error)=> console.warn("fetch Error: ", error));
}
renderPhotos() {
return this.state.photos.map( photos =>
<GalleryDetail key={photos.id} photos= {photos}/>
);
}
render () {
return (
<View>
<ScrollView>
{this.renderPhotos()}
</ScrollView>
</View>
);
}
}
export default GalleryList;,我的GalleryDetail是
import React, {Component} from 'react';
import { Text, View, Image } from 'react-native';
import Card from './Card';
import CardSection from './CardSection';
const GalleryDetail = (props)=> {
return (
<Card>
<CardSection style = {styles.headerContentStyle}>
<Image
style={styles.thumbnailStyle}
source = {{ uri: props.photos.thumbnailUrl}}/>
<Text style= {styles.textStyle}>{props.photos.title}</Text>
</CardSection>
</Card>
);
};
const styles = {
headerContentStyle: {
flexDirection: 'column',
justifyContent: 'space-around'
},
thumbnailStyle: {
height: 50,
width: 50
},
textStyle: {
textAlign: 'right',
marginLeft: 3,
marginRight: 3,
}
}
export default GalleryDetail;很抱歉没有提供适当的片段。请帮帮忙
发布于 2017-12-28 05:38:51
首先,您应该使用componentDidMount进行网络调用,正如文档所解释的那样。
第二,不要使用ScrollView,因为它不是表演性的,当使用FlatList时,您不再需要ScrollView了。
第三,更新GalleryDetail以使用props.photo而不是props.photos,因为您将单个对象传递给每一行(复数使其与直觉相反)。并通过照片对象中的item属性访问数据:
const GalleryDetail = (props)=> {
return (
<Card>
<CardSection style = {styles.headerContentStyle}>
<Image
style={styles.thumbnailStyle}
source = {{ uri: props.photo.thumbnailUrl}}/>
<Text style= {styles.textStyle}>{props.photo.title}</Text>
</CardSection>
</Card>
);
};最后,使用以下代码片段
render() {
if (!this.state.photos) {
return <ActivityIndicator/>;
}
return (
<FlatList
data={this.state.photos}
keyExtractor={this.keyExtractor}
renderItem={this.renderPhoto}
/>
);
}
keyExtractor = (photo, index) => photo.id;
renderPhoto = ({item}) => {
return < GalleryDetail photo={item} />;
};https://stackoverflow.com/questions/47999759
复制相似问题