React Native - получение состояния `location` в моем React Redux Store - PullRequest
1 голос
/ 11 июня 2019

Я пытаюсь получить мое состояние location (долгота и широта) в моем React Redux Store, чтобы создать несколько маркеров MapView, но он возвращает эту ошибку:

enter image description here

Вот мои коды:

EventMap.js - здесь я хочу использовать Redux State и создать несколько MapView Marker. Я пытался применить состояние Redux с координатами MapView.Marker.

this.state = {
  focusedLocation: {
    latitude: 0,
    longitude: 0,
    // latitudeDelta: 0.04864195044303443,
    // longitudeDelta: 0.040142817690068,
    latitudeDelta: 0.01,
    longitudeDelta: Dimensions.get('window').width / Dimensions.get('window').height * 0.01
  },
  },
  markers: [
    {
      coordinate: {
        latitude: 37.42484589323653,
        longitude: -122.08271104842426
      },
    },
    {
      coordinate: {
        latitude: 37.42019338901534,
        longitude: -122.08207536488771
      },

    },
    {
      coordinate: {
        latitude: 37.4219108525511,
        longitude: -122.08126466721296
      },
    },
    {
      coordinate: {
        latitude: 37.42190153308783,
        longitude: -122.08728086203337
      },
    },
    {
      coordinate: {
        latitude: 37.419681603891306,
        longitude: -122.08521489053966
      },
    }
  ],
}

<MapView
      style={styles.container}
      initialRegion={this.state.focusedLocation}
      onPress={this.pickLocationHandler}
      showsUserLocation={true}
      ref={ref => this.map = ref} //For animating map movement
    >
      {userMarker}
      {this.props.events.map((marker, index) => {
        if(marker.location) {
          const scaleStyle = {
            transform: [
              {
                scale: interpolations[index].scale,
              },
            ],
          };
          const opacityStyle = {
            opacity: interpolations[index].opacity,
          };
          return (
            <MapView.Marker key={index} coordinate={marker.location}>
              <Animated.View style={[styles.markerWrap, opacityStyle]}>
                <Animated.View style={[styles.ring, scaleStyle]} />
                  <View style={styles.marker} />
              </Animated.View>
            </MapView.Marker>
          );
        } else {
          return null;
        }
      })}
    </MapView>

---------------
const mapStateToProps = state => {
return {
  events: state.events.events
};
};

export default connect(mapStateToProps)(EventMap);

EventCreator.js:

placeAddedHandler = () => {
this.props.onAddEvent(
  this.state.controls.eventName.value,
  this.state.controls.eventDescription.value,
  this.state.controls.location.value
);
};

render() {
return(
  <LinearGradient style={styles.linearGradient} colors={['#718792', '#1c313a', '#000a12']}>
    <View style={{flex:1}}>
      <SetLocationMap 
        mapContainer={styles.mapContainer}
        onLocationPick={this.locationPickedHandler}
        showUserLocation={true}
      />
    </View>
    <View style={styles.buttonContainer}>
      <TouchableOpacity onPress={this.placeAddedHandler}>
        <View style={styles.button}>
          <Text style={{color: 'black', fontSize: 20, fontWeight: 'bold'}}>Add</Text>
        </View>
      </TouchableOpacity>
    </View>
  </LinearGradient>
);
} 
}

SetLocationMap.js:

  pickLocationHandler = (event) => {
const coords = event.nativeEvent.coordinate;
//For animation of map
this.map.animateToRegion({
  ...this.state.focusedLocation,
  latitude: coords.latitude,
  longitude: coords.longitude
});
this.setState(prevState => {
  return {
    focusedLocation: {
      ...prevState.focusedLocation,
      latitude: coords.latitude,
      longitude: coords.longitude
    },
    locationChosen: true
  };
});
this.props.onLocationPick({
  latitude: coords.latitude,
  longitude: coords.longitude
});
};

  render() {
let marker = null;
if(this.state.locationChosen) {
  marker = <MapView.Marker coordinate={this.state.focusedLocation} flat={true}/>
}
return(
  <View style={this.props.mapContainer}>
    {/* <TouchableOpacity onPress={this.getLocationHandler} style={styles.iconContainer}>
      <Icon name="md-locate" size={30} color="blue"/>
    </TouchableOpacity> */}
    <MapView
      {...this.props}
      style={styles.map}
      initialRegion={this.state.focusedLocation}
      onPress={this.pickLocationHandler}
      ref={ref => this.map = ref} //For animating map movement
    >
      {marker}
    </MapView>
  </View>
);
}
}

Вот мои коды для React Redux:

../store/reducers/events.js - this is where I put my React Redux State

const reducer = (state = initialState, action) => {
switch (action.type) {
  case ADD_EVENT:
    return {
       ...state,
      events: state.events.concat({
        key:  `${Math.random()}`,
        name: action.eventName,
        description: action.eventDescription,
        location: action.location,
        image: {
          uri: "https://c1.staticflickr.com/5/4096/4744241983_34023bf303_b.jpg"
        }
      })
    };

Если чего-то не хватает, спросите у меня мои коды. Спасибо!

1 Ответ

1 голос
/ 11 июня 2019

Возможно, проблема в вашем коде заключается в следующем:

<MapView.Marker key={index} coordinate={this.props.events}> 

Где this.props.events - это нечто (в зависимости от вашего состояния), отличающееся от типа местоположения.

Попытка решения состоит в том, чтобы попытаться указать тип местоположения, например:

<MapView.Marker key={index} coordinate={{latitude: latitude, longitude: longitude}}> 

, где широта и долгота - число с плавающей точкой.

Пример:

<MapView.Marker key={index} coordinate={{latitude: 4.3414303 , longitude: 15.3277476}}> 

Обновление : Если вы хотите отобразить местоположение, предоставленное событиями в вашем штате, вы можете сделать следующее: Я предполагаю, что местоположение в вашем штате является типом местоположения ({широта: широта, долгота: долгота}), вы можете выполнить цикл this.props.events:

<MapView
      style={styles.container}
      initialRegion={this.state.focusedLocation}
      onPress={this.pickLocationHandler}
      showsUserLocation={true}
      ref={ref => this.map = ref} //For animating map movement
    >
      {userMarker}
      {this.props.events.map((marker, index) => {
        if(marker.location.latitude && marker.location.longitude) {
            const scaleStyle = {
              transform: [
                {
                  scale: interpolations[index].scale,
                },
              ],
            };
            const opacityStyle = {
              opacity: interpolations[index].opacity,
            };
            return (
              <MapView.Marker key={index} coordinate={marker.location}>
                <Animated.View style={[styles.markerWrap, opacityStyle]}>
                  <Animated.View style={[styles.ring, scaleStyle]} />
                    <View style={styles.marker} />
                </Animated.View>
              </MapView.Marker>
            );
        } else {
            return null;
        }
      })}
    </MapView>
...