You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用useSelector获取react-native-maps定位数据时触发TypeError的排查

解决TypeError: Cannot read property 'location' of null(Uber克隆应用Map组件)

错误原因

你的Redux初始状态中origin被设为null,当Map组件首次渲染时,useSelector(selectOrigin)获取到的origin值为null,此时直接访问origin.location就会触发类型错误。

解决方案

方案1:给初始区域设置默认值

在origin为null时,提供一个兜底的初始地图区域,避免直接访问null的属性:

import { StyleSheet, Text, View } from 'react-native';
import React from 'react';
import MapView, { Marker } from 'react-native-maps';
import tw from 'tailwind-react-native-classnames';
import { useSelector } from 'react-redux';
import { selectOrigin } from '../slices/navSlice';

const Map = () => {
  const origin = useSelector(selectOrigin);

  return (
    <MapView 
      style={tw`flex-1`}
      mapType="mutedStandard"
      initialRegion={origin ? {
        latitude: origin.location.latitude,
        longitude: origin.location.longitude, 
        latitudeDelta: 0.005,
        longitudeDelta: 0.005,
      } : {
        // 示例默认坐标(可替换为你需要的初始位置)
        latitude: 40.7128,
        longitude: -74.0060,
        latitudeDelta: 0.01,
        longitudeDelta: 0.01,
      }}
    />
  );
};

export default Map;

const styles = StyleSheet.create({});

方案2:条件渲染Map组件

先判断origin是否存在,不存在时显示提示或加载状态,存在再渲染地图:

import { StyleSheet, Text, View } from 'react-native';
import React from 'react';
import MapView, { Marker } from 'react-native-maps';
import tw from 'tailwind-react-native-classnames';
import { useSelector } from 'react-redux';
import { selectOrigin } from '../slices/navSlice';

const Map = () => {
  const origin = useSelector(selectOrigin);

  // origin未设置时显示提示
  if (!origin) {
    return (
      <View style={tw`flex-1 justify-center items-center bg-white`}>
        <Text style={tw`text-gray-600`}>请先选择出发地点</Text>
      </View>
    );
  }

  return (
    <MapView 
      style={tw`flex-1`}
      mapType="mutedStandard"
      initialRegion={{
        latitude: origin.location.latitude,
        longitude: origin.location.longitude, 
        latitudeDelta: 0.005,
        longitudeDelta: 0.005,
      }}
    />
  );
};

export default Map;

const styles = StyleSheet.create({});

额外检查点

  • 确认setOrigin动作是否在Map组件渲染前被正确触发:比如在搜索地点的组件中,用户选择地点后,是否调用了dispatch(setOrigin(xxx)),且传入的payload包含location属性。
  • 检查setOrigin的payload结构:必须是类似{ location: { latitude: 数值, longitude: 数值 }, description: "地点描述" }的格式,确保origin.location能被正确访问。

内容的提问来源于stack exchange,提问作者Josh Brice

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.20 20:10:24