Openlayers setState on Select event

user3566338 :

I am trying to trigger a React setState when a feature is clicked. I try to edit the selectedFeature and show it's properties on the screen. But I get a "TypeError: Cannot read property 'setState' of undefined" Error message every time i try to execute the click method.

componentDidMount() {
    ...

    function featureSelected(event) {
      console.log(event.selected[0].getProperties());
      this.setState({ selectedFeature: event.selected[0].getProperties() });
    }

    var changeInteraction = function() {
      var select = new Select({});
      select.on("select", event => featureSelected(event));
      map.addInteraction(select);
    };

    ...
}

This is the line that throws the error:

 this.setState({ selectedFeature: event.selected[0].getProperties() });

This is my state property:

class MyMap extends Component {
  state = {
    selectedFeature: null
  };
...
Joe Lloyd :

This is undefined

Use fat arrow function instead of the function keyword. You add a new scope when you add a function. this becomes the this of the function and not of the class anymore.

A fat arrow function passes the scope of this down and will allow you to call class methods like setState.

componentDidMount() {
    ...

    const featureSelected = (event) => {
      console.log(event.selected[0].getProperties());
      this.setState({ selectedFeature: event.selected[0].getProperties() });
    }

    var changeInteraction = () => {
      var select = new Select({});
      select.on("select", event => featureSelected(event));
      map.addInteraction(select);
    };

    ...
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=29998&siteId=1