Flatlist多次显示相同的项目

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

我正在使用平面列表从api呈现数据,这些数据也被呈现并显示。但是问题是项目被多次显示。我从api中获得了5个项目,但是那5个项目正在重复。

enter image description here

我已经实现如下:

export default class FlatSpeakers extends Component {
constructor(props) {
    super(props);
    this.state = { isLoading: true, data: [] }
}
componentDidMount() {
    axios.get('https://rallycoding.herokuapp.com/api/music_albums')
       .then(res => {
            this.setState({
                isLoading: false,
                data: res.data,
            })
        })
}
renderItem() {
    return (
        this.state.data.map(item =>
          <SpeakersDetails key={item.title} speakerD={item} />
        )
      )
}

render() {
    if (this.state.isLoading) {
        return (
           <View style={{ flex: 1, padding: 20 }}>
                <ActivityIndicator />
            </View>
        )
    }

    return (
        <View style={styles.container}>
            <FlatList
                data={this.state.data}
                renderItem={this.renderItem.bind(this)}
                keyExtractor={item => item.id}
            />
        </View>
    );
}
}

我已经实现了SpeakersDetails组件,如下所示:

const SpeakersDetails = ({ speakerD }) => {

const { title, artist, thumbnail_image, image, url } = speakerD;
const {
    thumbnailStyle,
    headerContentStyle,
    thumbnailContainerStyle,
    headerTextStyle,
    imageStyle
} = styles;

return (
    <Card>
        <CardSection>
            <View style={thumbnailContainerStyle}>
                <Image
                    style={thumbnailStyle}
                    source={{ uri: image }}
                />
            </View>
            <View style={headerContentStyle}>
                <Text style={headerTextStyle}>{title}</Text>
                <Text>{artist}</Text>
            </View>
        </CardSection>
    </Card>
);
 };
react-native react-native-flatlist
1个回答
1
投票

[FlatList遍历data并为其中的每个项目调用renderItem,您将在每次调用时呈现完整列表,这就是为什么要重复项目的原因。

renderItem接收当前项目作为参数,尝试像这样更改您的功能:

renderItem({item}) {
    return (
          <SpeakersDetails key={item.title} speakerD={item} />
      )
}

检查renderItem documentation了解更多详细信息,包括此功能接收的其他参数。

© www.soinside.com 2019 - 2024. All rights reserved.