Reactjsで画像のBase64表現をサーバから取得し表示するコンポーネントを作成しています。コードは以下のとおりです。
DataImage.react.js
import React, { Component } from 'react';
import DataImageStore from '../../stores/DataImageStore';
import DataImageActions from '../../actions/DataImageActions';
export class DataImage extends Component{
static propTypes = {
path: React.PropTypes.string.isRequired
}
constructor(props){
super(props);
this.state = this.getDataImageState();
this.onStateChanged = this.onStateChanged.bind(this);
}
componentWillMount(){
DataImageActions.fetchImage(this.props.path);
}
componentDidMount(){
DataImageStore.addChangeListener(this.onStateChanged);
}
componentDidUnMount(){
DataImageStore.removeListener(this.onStateChanged);
}
getDataImageState(){
return {
image: DataImageStore.getImage()
}
}
onStateChanged(){
this.setState(this.getDataImageState());
}
render(){
return <img src={this.state.image}/>
}
}
DataImageStore.js
import AppDispatcher from '../dispatcher/AppDispatcher';
import { EventEmitter } from 'events';
import DataImageConstants from '../constants/DataImageConstants';
class DataImageStore extends EventEmitter {
constructor(){
super();
AppDispatcher.register(this.onAction.bind(this));
this.CHANGE_EVENT = 'change';
this.image = "";
}
onAction(action){
switch(action.actionType){
case DataImageConstants.DATA_IMAGE_RECEIVED:
this.image = action.image;
this.emitChange();
break;
default:
}
}
getImage(){
return this.image;
}
emitChange(){
this.emit(this.CHANGE_EVENT);
}
addChangeListener(callback){
this.on(this.CHANGE_EVENT, callback);
}
removeListener(callback){
this.removeChangeListener(this.CHANGE_EVENT, callback);
}
}
let store = new DataImageStore();
export default store;
DataImageActions.js
import AppDispatcher from '../dispatcher/AppDispatcher';
import DataImageConstants from '../constants/DataImageConstants';
import DataImageUtils from '../utils/DataImageUtils';
export default {
fetchImage: (path) => {
AppDispatcher.dispatch({
actionType: DataImageConstants.DATA_IMAGE_FETCH
});
DataImageUtils.fetch(path);
},
receiveImage: (image) => {
AppDispatcher.dispatch({
actionType: DataImageConstants.DATA_IMAGE_RECEIVED,
image: image
});
}
}
DataImageConstants.js
import keyMirror from 'keymirror';
export default keyMirror({
DATA_IMAGE_FETCH: null,
DATA_IMAGE_RECEIVED: null
});
DataImageUtils.js
import request from 'superagent';
import DataImageActions from '../actions/DataImageActions';
export default {
fetch: (path) => {
request
.get('/image/')
.query({
path: path
})
.end((err, res) => {
if(err) return console.error(err);
DataImageActions.receiveImage(res.text);
});
}
}
しかし、このクラスの親コンポーネントでpathを取得しViewを更新するとタイトルのようなエラーが出ます。どのように修正すれば上のエラーを解決できるのでしょうか。教えて下さい。よろしくお願いします。