更新 React 状态时渲染内部自调用函数出错

Error in self-invoking function inside render when updating React state

我正在使用自调用函数中的 react-native-maps. On my map, I am dynamically populating a number of circles by using the map 方法编写 React Native 应用程序。请参阅组件的渲染函数中的以下代码:

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

这在初始渲染时效果很好。我稍后根据用户在地图上点击的位置更新 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>
    );
  }

答案原来是 stateCopy 类型不正确。由于 this.state.mapviewPolygon 是对象数组,因此使用 Object.assign 是错误的。所以我替换了这个:

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

有了这个:

let stateCopy = [];
  for (let i in this.state.mapviewPolygon) {
    stateCopy.push(this.state.mapviewPolygon[i]);
};

这是可行的,因为 map 现在正在接收一个数组而不是一个对象。

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

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

map 不是对象的方法;因此错误。如果你想复制一个数组,使用类似的东西:

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

或者

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