Uncaught TypeError: this.setState is not a function in React

时间:2016-11-26 18:39:22

标签: javascript reactjs

This is a weird problem that I started getting out of nowhere.

I have container component that receives data from child components.

This is the constructor where I am declaring the state and binding the functions that will be modifying the state.

class HomePage extends React.Component{

  constructor(props){
    super(props);
    this.getSelectedImage = this.getSelectedImage.bind(this);
    this.getTargetId = this.getTargetId.bind(this);
    this.handleSend = this.handleSend.bind(this);
    this.state = { targetId: null, targetImage: null };
  }

Now I have this function, which changes one state,

getSelectedImage(image){

    this.setState({ targetImage: image });
    console.log(this.state.targetImage.id);

  }

This works fine. But then I have this,

getTargetId(target){
    console.log(target);
    this.setState({ targetId: target });
  }

This fails with the error,

Uncaught TypeError: this.setState is not a function

I can console.log the target, so the data is getting passed up right, but then I can't seem to use the same target value to change state, using the exact same logic for changing the state of the other object.

What am I doing wrong here?

0 个答案:

没有答案