无法在React本机应用程序内有效滚动

问题描述 投票:0回答:1

我只是一个初学者,并一直致力于一个需要尽快完成的项目。我通过API获取了超过5000个数据列表,但是列表在滚动方面效率不高,从而破坏了应用程序。我一直在寻找FlatList中的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;

很抱歉没有提供正确的代码段。请帮忙

reactjs listview react-native redux react-native-flatlist
1个回答
0
投票

首先,您应该在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} />;
  };
© www.soinside.com 2019 - 2024. All rights reserved.