Why is my react component not updating with state updates?

前端 未结 1 1050
清酒与你
清酒与你 2021-02-19 18:18

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

相关标签:
1条回答
  • 2021-02-19 19:05

    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
    
    
    }
    
    0 讨论(0)
提交回复
热议问题