Why is my react component not updating with state updates?

前端 未结 2 1842
无人及你
无人及你 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
    
    
    }
    
    0 讨论(0)
  • 2021-02-19 19:17
    .then((response) => {
        this.setState({events: resp});
    }
    

    You take in parameter response then try to use resp which isnt the variable you want.

    0 讨论(0)
提交回复
热议问题