Justin Justin - 1 month ago 18
React JSX Question

access component `this` from container

I'm using props to pass in functions that my component needs to run. Keeping the component as dumb as possible. Instead of putting into the functions into the react class.

I need to update my component state, but I'm having trouble accessing setState from within my prop function. I've tried doing something like, so my function can access it, but I keep getting an error:

Component

componentDidMount(){
this.props.loadImage(this.props.src).bind(this);
}


Container Load Image Function

let loadImage = (src)=>{
console.log('loading Image');
fetch(src).then(function( data ) {
console.log('success');
that.setState({'imgUrl':src});
}).catch(function( error ) {
console.log('fail');
setTimeout(loadImage(src), 1000);
});

};


Error:

component.js:67 Uncaught TypeError: Cannot read property 'bind' of undefined(…)



  1. Why is bind undefined on this prop function?

  2. Am I just approaching this the wrong way?



Thanks!

Answer

If loadImage doesn't return a function then you are probably calling bind on undefined. You might want to do this.props.loadImage.bind(this, this.props.src); instead.