简体   繁体   English

为什么我的react组件没有更新状态更新?

[英]Why is my react component not updating with state updates?

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 new sports property from it's parents component : 我有一个我构建的地图应用程序,需要一些地图图标在按下按钮后显示/消失,但我无法弄清楚当我从它的父项组件传入一个新的体育属性时如何设置它来重新渲染组件:

Parent loads component: 父加载组件:

<SimpleMap sports=[default value and future values go here] />

Simple map component(simplified): 简单的地图组件(简化):

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"]
  };
};

componentWillReceiveProps (nextProps) {
  this.setState({events: [{venue: {lat: 2, lon: 1}}],
                  sports: nextProps.sports});
  console.log(nextProps.sports);
}

static defaultProps = {
  center: {lat: 36.160338, lng: -86.778780},
  zoom: 12,
  sports: ["baseball", "football",  "paddle", "soccer", "boxing", "dart", "biking", "golf", "hockey", "inline-skating", "tennis", "volleyball", "skateboard", "kickball", "bowling", "pool", "ride", "hike", "ice-skating"],
};

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});
  }
};

componentDidMount () {
  this.makeMapEvents(this.state.sports);
  console.log("mounted", this.state.sports);
}

Eventually ends up here to map events from state: 最终到这里来映射来自州的事件:

<GoogleMap>
  {this.state.events.map((result) => {
     return (<Marker key={counter++} lat={result.venue.lat} lng={result.venue.lon} 
                sport={this.props.sport} data={result}/>);
  })}
</GoogleMap>

React ES6 classes do not autobind this by default to non-react base member methods. 反应ES6类不autobind this默认非反应基构件的方法。 Therefore, the context for this in your function makeMapEvents is not bound correctly. 因此,对于上下文this在功能makeMapEvents不正确绑定。 There are 2 ways to fix this: 有两种方法可以解决这个问题:

Via ES7 property initializer: 通过ES7属性初始化程序:

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


}
.then((response) => {
    this.setState({events: resp});
}

You take in parameter response then try to use resp which isnt the variable you want. 您接受参数response然后尝试使用不是您想要的变量的resp

The probable cause is that your makeMapEvents() function doesn't provide the correct lexical value of this when calling this.setState() and as a result your code doesn't work. 可能的原因是,你的makeMapEvents()函数不提供正确的词汇值this打电话时this.setState()因此您的代码不起作用。 Change the makeMapEvents() function definition to use Arrow function ( () => {} ) and provide correct lexically bound value of this as: 更改makeMapEvents()函数定义以使用箭头函数() => {} )并提供正确的词法绑定值:

makeMapEvents = (insertProps) => {
  fetch("./json/meetup.json").then((response) => {
    return response.json()
  }).then((response) => {
    this.setState({events: response});
  }); // <-- Typo here. The closing parenthesis is missing
};

Also there is a typo in your code wherein the closing parenthesis is missing as shown in comments above 此外,您的代码中还有一个拼写错误,其中缺少右括号,如上面的注释所示

You are mixing up props and state in the component. 你在组件中混合道具和状态。 sports should only be in props, it shouldn't be in state as it is being passed in from the parent component. sports应该只在props中,它不应该处于从父组件传入的状态。

constructor(props) {
  (props);
  this.state = {
    events: [{venue: {lat: 2, lon: 1}}] <== removed sports here, it didn't belong
};

componentWillReceiveProps (nextProps) {
  this.setState({events: [{venue: {lat: 2, lon: 1}}],
                  sports: nextProps.sports});
  console.log(nextProps.sports);
}

static defaultProps = {
  center: {lat: 36.160338, lng: -86.778780},
  zoom: 12,
  sports: ["baseball", "football",  "paddle", "soccer", "boxing", "dart", "biking", "golf", "hockey", "inline-skating", "tennis", "volleyball", "skateboard", "kickball", "bowling", "pool", "ride", "hike", "ice-skating"],
};

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});
  }
};

componentDidMount () {
  this.makeMapEvents(this.props.sports);  <== changed to props.sports
  console.log("mounted", this.props.sports); <== changed to props.sports
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM