【问题标题】:Getting components to refresh with dynamic property changes使用动态属性更改使组件刷新
【发布时间】:2015-12-26 21:15:32
【问题描述】:

我正在编写一个混合使用 Geolocation API 和用户输入位置的应用,并使用 ReactJS 构建。

该应用程序同时具有地图视图窗格和列表视图窗格;这两者的容器(React 术语中的“父”或“所有者”)是设置地理位置的内容。

所以,容器是这样的:

var App = React.createClass({
/**
Internal callback used by Geolocation API
**/
setPosition: function(position){
    var lat = position.coords.latitude;
    var longitude = position.coords.longitude;
    this.setState({location: {lat:lat, lng:longitude}});        
},
getInitialState: function(){
    return {location: null, statusText: 'Finding you...'}
},
componentDidMount: function(){
/* First use current position on first load */
    if (!navigator.geolocation){
        this.setState({statusText: 'No Geolocation!'});
    }
    else{
        navigator.geolocation.getCurrentPosition(this.setPosition, this.errorPosition);
    }
},
render: function(){
    return(
            <SearchLocator biasLocation={this.state.location} 
                           statusProp={this.state.statusText} />
    )


}
)};

“SearchLocator”组件执行 Google Places 搜索。并依次包含地图窗格和列表窗格:

var SearchLocator = React.createClass({
render: function(){
 return(<div>
    <GeoSuggest onSuggestSelect={this.handleSuggestion} />
    <MapAndListContainer locationProp={this.state.location} />
 </div>)
};
)};

最后,“MapAndListContainer”将位置属性向下传递到地图窗格和列表窗格。因此,如您所见,位置属性以对象的形式呈现,看起来像

{location: {lat: latValue, lng: lngValue}}

在 setState 中使用并作为属性传递给子级。

问题:我只是让“初始状态”道具工作 - 也就是说,无论应用程序容器(最顶层的父级)中的默认初始状态是什么。但是当位置发生变化时,这些变化不会传播到整个孩子。我应该使用: 1.组件应该更新? 2.“钥匙”的属性? 3. 强制更新? 4. 还有什么我忽略的?

我是一名 React 新手,我会喜欢任何和所有的指针!

【问题讨论】:

  • 你不需要做这四件事中的任何一件。我希望您的代码在某处存在一些问题。您似乎在 SearchLocator 元素上设置了很多道具,而没有实际使用。您是否也尝试过使用 react 开发者工具调试每个元素的状态?你能告诉我应用开始运行后每个元素的状态/道具是什么吗?
  • @Miguel :首先,这里有一个指示性要点:gist.github.com/nonystack/f2587f6a834d12ac39d4 SearchLocator 上设置的道具供 SearchLocator 的孩子使用,它们是“Google Places”建议文本区域和实际地图。这都是由经纬度触发的。应用程序开始运行后,默认的 lat 和 lng 是虚拟的,因为传递 null 道具是一个问题。但后来该应用程序反映了地理定位 API 更新。孩子们没有。

标签: google-maps reactjs geolocation google-places-api


【解决方案1】:

如果可以解决您的问题,请尝试:

<MapAndListContainer locationProp={this.props.biasLocation} />

this.props.biasLocation 而不是this.state.location 传递给子MapAndListContainer

【讨论】:

  • 这里的问题是 SearchLocator 必须保持其位置的状态,并且任何传递给 SearchLocator 子级的 props 都必须反映状态的变化。这是一个很好的猜测,但它并没有解决我的问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-01-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-08-11
相关资源
最近更新 更多