[英]setState on specific key with ReactJS
I read on some tutorials that we can pass a specific key in parameters of setState in order to update only specific elements. 我阅读了一些教程,我们可以在setState的参数中传递特定键,以便仅更新特定元素。 But here is my case : 但是这是我的情况:
I use tomchentw's react-google-maps component. 我使用tomchentw的react-google-maps组件。 I set the options of the map in my App state (then I pass it to the GoogleMap component via props). 我将地图选项设置为“我的应用”状态(然后通过道具将其传递给GoogleMap组件)。
app.jsx app.jsx
constructor() {
super();
//Initial value
this.state = {
optionsMap:{
center: {
lat: 46.8261444,
lng: 2.2418121
},
zoom: 5
},
variables: {}
}
}
map.jsx map.jsx
render() {
return (
<GoogleMapLoader
containerElement={ <div {...this.props} style={{ height: '500px'}}></div> }
googleMapElement={
<GoogleMap
ref="googleMap"
{...this.props.optionsMap} //biding map options with spread
onIdle={this._handleIdle.bind(this)}>
</GoogleMap>
}
/>
);
}
_handleIdle(event) {
this.props.updateVarsOptions(this.props.optionsMap);
}
When I call my updateVarOptions() function (when I moove the map) define in app.jsx, I update the state on the very specific key variables . 当我在app.jsx中调用我的updateVarOptions()函数(在移动地图时)定义时,我会更新非常特定的键变量的状态 。
app.jsx app.jsx
_updateVarsOptions(mapOptions) {
this.setState({
variables : mapOptions
});
}
So, I update only the variables key on the state, but when I do the setState, the map is resettings with the default value (center position and zoom). 因此,我只更新状态上的变量键,但是当我执行setState时,地图将使用默认值(中心位置和缩放)进行重置。 The state is updating the optionsMap key to. 状态正在将optionsMap键更新为。 I don't understand why. 我不明白为什么。
The reason why your map is updating with the default values from optionsMap
is because any call to setState
will cause the component to re-render (unless there is behavior defined in shouldComponentUpdate
that says otherwise). 您的地图使用optionsMap
的默认值进行更新的原因是,对setState
任何调用都将导致组件重新呈现(除非在shouldComponentUpdate
中定义的行为另有说明)。 This, in turn, will re-render your Google Maps element and pass the information from the optionsMap
again, which has not changed since the initial render. 反过来,这将重新渲染您的Google Maps元素,并再次传递来自optionsMap
的信息,自初始渲染以来该信息未发生变化。
You might want to take a look at the shouldComponentUpdate
lifecycle function . 您可能需要看一看shouldComponentUpdate
生命周期函数 。 This function is involked immediately before rendering, and its return value will tell your component whether or not it should call its render
function again. 即将在渲染之前调用此函数,并且它的返回值将告诉您的组件是否应该再次调用其render
函数。 By default, it always returns true. 默认情况下,它始终返回true。 You can modify this behavior such that your component will not re-render if the variables
state has changed. 您可以修改此行为,以便如果variables
状态已更改,则组件将不会重新呈现。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.