2016-04-12 4 views
0

У меня есть компонент галереи, который демонстрирует изображения из компонентов prop.React Uncaught TypeError: Не удается прочитать свойство 'currentIndex' из null

Компонент галереи показывает 1 изображение за раз, но имеет 2 загруженных случайных формы массива для анимационных целей.

Все звучит замечательно, но я получаю эту ошибку в консоли

Uncaught TypeError: Cannot read property 'currentIndex' of null 

Не знаю, почему это было бы пустым.

Вот компонент ViewGallery.js:

import React from 'react'; 


class ViewGallery extends React.Component { 

    getInitialState(){ 
    return { 
     currentIndex: 0, 
     count: 0 
    }; 
    } 

    generateImagesDOM(){ 
    return imagesDOM; 
    } 

handleClick() { 
    let currentIndex = this.state.currentIndex; 

    if(currentIndex === this.state.count - 1){ 
     currentIndex = 0; 
    } else { 
     currentIndex ++; 
    } 

    this.setState({ 
     currentIndex: currentIndex 
    }); 


    $(this.images[currentIndex]).removeClass('active'); 

    } 

    render() { 
    let images = this.props.images; 
    let startWith = this.props.startWith; 
    let count = this.props.count; 
    let imagesDOM = []; 
    let i = startWith || 0; 

    if(typeof count === 'number' && count > 0){ 
     images = images.slice(0, count - 1); 
    } 

    let length = images.length; 

    if(startWith > 0 && startWith < length){ 
     let images0 = images.slice(0, startWith); 
     let images1 = images.slice(startWith); 
     images = images1.concat(images0); 
    } 


    for (; i<length ; i+=1) { 

     let className = "image"; 
     if(i === this.state.currentIndex){ 
     className += " active"; 
     } 
     imagesDOM.push(<div className={className}><img src={images[i]} /></div>); 
    } 

    this.state.count = length; 

    return <div className="gallery" onClick={this.handleClick}>{imagesDOM}</div> 
    } 
} 

ViewGallery.propTypes = { 
    images: React.PropTypes.array.isRequired, 
    startWith: React.PropTypes.number, 
    count: React.PropTypes.number 
} 

export default ViewGallery; 
+0

'bind' ваше событие' handleClick' для 'this' ->' this.handleClick.bind (this) ' –

ответ

1

При использовании class шаблона для создания Реагировать компоненты, вы должны установить начальное состояние в конструкторе, а не в getInitialState(). не

class ViewGallery extends React.Component { 

    constructor(props) { 
    super(props); 

    this.state = { 
     currentIndex: 0, 
     count: 0 
    }; 
    } 

    /* rest of your code */ 
} 

Кроме того, ваши методы, в отличие от предыдущего createClass рисунка, больше не связаны автоматически экземпляр компонента, вы должны связать их самостоятельно. Либо:

onClick={this.handleClick.bind(this)} 

или

onClick={e => this.handleClick(e)} 

См this blog post from 2015 January о различиях между extends React.Component и React.createClass() компонентных моделей создания.

Смежные вопросы