TypeError:TypeError:未定义不是对象(正在评估“ _this.state.scheduleList”)

时间:2019-12-13 03:16:32

标签: javascript react-native

export default class ScheduleDayTest extends React.Component {
constructor(props) {
    super(props);

    this.state = {
        scheduleList: [
            {
                id: 1,
                title: 'Arrival & Registration',
                type: 'Organizational',
                time: '3:00 PM',
                location: 'Main Lobby',
                message: 'Arrival at this time',
            },
            {
                id: 2,
                title: 'English Program Opening Statement',
                type: 'English Program',
                time: '6:00 PM - 6:30 PM',
                location: 'Lilac AC',
                message: 'Welcome to the 32nd annual conference',
            },
            {
                id: 3, 
                title: 'Arabic Program Opening Statement',
                type: 'Arabic Program',
                time: '6:00 PM - 6:30 PM',
                location: 'Lilac BD',
                message: 'Welcome to the 32nd annual conference',
            },
            {
                id: 4,
                title: 'Opening Ceremony',
                type: 'Organizational',
                time: '8:00 PM - 10:00 PM',
                location: 'Harry Ballroom',
                message: 'Opening Ceremony',
            },
          ],
        index: this.getIndex(this.props.navigation.state.params.itemID),
    }

}

getIndex = (itemID) => {
    for(let i = 0; i < this.state.scheduleList.length; i++) {
        if (this.state.scheduleList[i].id === itemID) {
            console.log(i);
            return i;
        }
    }
    return 0;
}

我试图调用getIndex函数来初始化索引状态变量,但是我不断收到这样的错误消息:即使声明了它,“ this.state.scheduleList”也不存在。任何帮助都会很棒。

1 个答案:

答案 0 :(得分:1)

您在初始化状态时正在调用getIndex,因此它将是未定义的。 请尝试以下

export default class ScheduleDayTest extends React.Component {
    constructor(props) {
        super(props);

        const scheduleList = [
            {
                id: 1,
                title: 'Arrival & Registration',
                type: 'Organizational',
                time: '3:00 PM',
                location: 'Main Lobby',
                message: 'Arrival at this time',
            },
            {
                id: 2,
                title: 'English Program Opening Statement',
                type: 'English Program',
                time: '6:00 PM - 6:30 PM',
                location: 'Lilac AC',
                message: 'Welcome to the 32nd annual conference',
            },
            ...
        ];
        this.state = {
            scheduleList,
            index: scheduleList.findIndex(item => item.id === this.props.navigation.state.params.itemID),
        }

    }   
}