Why is my react component not updating with state updates?

前端 未结 2 1880
无人及你
无人及你 2021-02-19 18:51

I have a map app I built that requires some map icons to appear/disappear after a button press, but I can\'t figure out how to set it to re-render the component when I pass in a

2条回答
  •  迷失自我
    2021-02-19 19:08

    React ES6 classes do not autobind this by default to non-react base member methods. Therefore, the context for this in your function makeMapEvents is not bound correctly. There are 2 ways to fix this:

    Via ES7 property initializer:

    makeMapEvents = (insertProps) => {
      fetch("./json/meetup.json").then((response) => {
        return response.json()
      }).then((response) => {
        /* eventually returns new events object based on insertProps */
        this.setState({events: response});
      })
    };
    

    Via binding in constructor:

    constructor(props) {
      (props);
      this.state = {
        events: [{venue: {lat: 2, lon: 1}}],
        sports: ["baseball", "football",  "paddle", "soccer", "boxing", "dart", "biking", "golf", "hockey", "inline-skating", "tennis", "volleyball", "skateboard", "kickball", "bowling", "pool", "ride", "hike", "ice-skating"]
      };
    
      this.makeMapEvents = this.makeMapEvents.bind(this) // << important line
    
    
    }
    

提交回复
热议问题