2016-04-12 11 views
0

私は、コンポーネントpropの画像を表示するギャラリーコンポーネントを持っています。React Uncaught TypeError:nullのプロパティ 'currentIndex'を読み取ることができません

ギャラリーコンポーネントは、一度に1つの画像を表示しますが、アニメーションの目的で配列をランダムに2つロードしています。

すべてが素晴らしいサウンドが、私は、コンソールに

Uncaught TypeError: Cannot read property 'currentIndex' of null 

をこのエラーを取得しています、これはnullになり、なぜ知ってはいけません。

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

あなたの 'handleClick'イベントを' this'に 'bind'する - >' this.handleClick.bind(this) ' –

答えて

1

コンポーネントを反応させるの作成のためのclassパターンを使用して、あなたがいないgetInitialState()で、コンストラクタで初期状態を設定する必要があります。ここでは

はViewGallery.jsコンポーネントです。

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)} 

extends React.ComponentReact.createClass()コンポーネント作成のパターン間の違いにthis blog post from 2015 Januaryを参照してください。

関連する問題