gpt4 book ai didi

javascript - 更新 React 状态时 render 内自调用函数出错

转载 作者:行者123 更新时间:2023-12-03 01:16:57 28 4
gpt4 key购买 nike

我正在使用 react-native-maps 编写 React Native 应用程序。在我的 map 上,我动态填充了一些 circles通过使用 map自调用函数内的方法。请参阅位于组件渲染函数中的以下代码:

{
(() => {
return this.state.mapviewPolygon.map(circle => (
<MapView.Circle
center={circle.coordinates}
key={circle.key}
/>
))
})()
}

这在初始渲染上效果很好。稍后,我根据用户在 map 上点击的位置更新 this.state.mapviewPolygon,目的是让圆圈根据新的坐标集重新渲染。

但是,当此自调用函数触发时,我收到错误 TypeError: undefined is not a function (near '..._this2.state.mapviewPolygon.map...'),这并没有告诉我太多。同样,堆栈跟踪的帮助也可以忽略不计。

发生了什么事?如何让圆圈正确重新渲染?

编辑 1:请参阅下面的整个渲染函数:

render() {

return (
<View style={styles.container}>

<MapView
style={styles.map}
showUserLocation
followUserLocation
loadingEnabled
region={this.getMapRegion()}
scrollEnabled = {this.state.mapviewScroll}
onPress= { (e) => {
let stateCopy = Object.assign({}, this.state.mapviewPolygon);
// circleKey is a variable containing the index of
// the item in the state array to change
stateCopy[circleKey].coordinates = e.nativeEvent.coordinate;
this.setState({mapviewPolygon: stateCopy});
}
}
>

{
this.state.mapviewPolygon.map(circle =>
<MapView.Circle
center={circle.coordinates}
key={circle.key}
radius={50}
fillColor={'#4286f4'}
/>
)
}

<MapView.Polygon
coordinates={this.getPolygonCoords()}
fillColor="rgba(0, 200, 0, 0.5)"
strokeColor="rgba(0,0,0,0.5)"
strokeWidth={2}
/>
</MapView>

</View>
);
}

最佳答案

当您这样做时,您正在将mapviewPolygon从可能的数组更改为对象:

let stateCopy = Object.assign({}, this.state.mapviewPolygon);

map 不是对象的方法;因此出现错误。如果您想复制数组,请使用类似以下内容的内容:

let stateCopy = [...this.state.mapviewPolygon];

或者

let stateCopy = this.state.mapviewPolygon.slice();

关于javascript - 更新 React 状态时 render 内自调用函数出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51967797/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com