Javascript/React 本机循环仅将变量更新为最后一个值

Javascript/React Native looping only update variable to last value

我正在使用 React Native 循环来显示部分 header 和数据。

我的预期输出如下:

> Section 0

data1 data2

> Section 1

data1 data2

> Section 2

data1 data2

将根据循环次数循环播放该部分

然而,实际输出是这样的: Actual Output

只显示最后一个循环值

import React, { Component } from 'react';
    import { Text, StyleSheet, View, SafeAreaView, SectionList } from 'react-native';

    export default class Appointment extends Component {

        constructor(props) {
            super(props)

            this.state = {
                appointmentList: [{
                    index: '',
                    data: ['']
                }]
            }
        }

        componentDidMount() {

            let appointmentListItem = {};
            let appointment = [];

            for (let i = 0; i < 3; i++) {
                console.log(i);
                appointmentListItem.index = i;
                appointmentListItem.data = ['data1', 'data2'];
                appointment.push(appointmentListItem);
            }


            this.setState({
                appointmentList: appointment
            });


        }


        render() {
            return (
                <SafeAreaView>
                    <SectionList
                        sections={this.state.appointmentList}
                        keyExtractor={(item, index) => item + index}
                        renderItem={({ item }) => <Text>{item}</Text>}
                        renderSectionHeader={({ section: { index } }) => (
                            <View style={{ backgroundColor: 'red' }}>
                                <Text>{index}</Text>
                            </View>
                        )}
                    />

                </SafeAreaView>
            )
        }
    }

这个问题有什么解决办法吗?非常感谢

变量 appointmentListItem 被实例化一次,然后随着 for 循环的迭代而发生变异。这导致单个对象引用被多次添加到 appointment 列表中,最近的变化应用于所有引用的对象。

将变量appointmentListItem的声明移到for循环体中,像这样:

    componentDidMount() {

        let appointment = [];

        for (let i = 0; i < 3; i++) {
            console.log(i);
            const appointmentListItem = {}
            appointmentListItem.index = i;
            appointmentListItem.data = ['data1', 'data2'];
            appointment.push(appointmentListItem);
        }


        this.setState({
            appointmentList: appointment
        });


    }