javascript 为什么在react-native-maps组件中使用“useSelector”访问位置数据时会收到TypeError?[副本]

nwlls2ji  于 2023-05-27  发布在  Java
关注(0)|答案(1)|浏览(96)

此问题已在此处有答案

React Native render error: null is not an object (evaluating origin.location)(1个答案)
2天前关闭。

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={{
        latitude: origin.location.latitude,
        longitude: origin.location.longitude, 
        latitudeDelta: 0.005,
        longitudeDelta: 0.005,
      }}
    />
  );
};

export default Map;

const styles = StyleSheet.create({});;

这是我的代码,我试图创建一个超级克隆,但当我运行它时,我收到以下错误:ERROR TypeError: Cannot read property 'location' of null
下面是我的navSlice.js以供参考。

import { createSlice } from "@reduxjs/toolkit";

const initialState = {
  origin: null, 
  destination: null, 
  travelTimeInformation: null,
};

/* Data Layer*/
export const navSlice = createSlice({
  name: 'nav',
  initialState,
  reducers: {
    setOrigin: (state, action) => {
      state.origin= action.payload;
    },
    setDestination: (state, action) => {
      state.destination= action.payload;
    },
    setTravelTimeInformation: (state, action) => {
      state.travelTimeInformation= action.payload;
    },  
  },
});

export const {
  setOrigin,
  setDestination,
  setTravelTimeInformation
} = navSlice.actions;

// Selectors. Need one for each action

export const selectOrigin = (state) => state.nav.origin;
export const selectDestination = (state) => state.nav.destination;
export const selectTravelTimeInformation = (state) => 
  state.nav.travelTimeInformation;

// Reduce in our store.js file. Initially wrote and now connecting it. 
export default navSlice.reducer;

有人能帮我找出这里可能出了什么问题吗?
我试着看了一下文档,我不确定我会在哪里出错。我也有一个工作参考,我想我检查了相当彻底,但也许没有-任何想法?

8i9zcol2

8i9zcol21#

它似乎是一个空引用

const initialState={
    origin: null, 
    destination: null, 
    travelTimeInformation: null,
};

export const selectOrigin = (state) => state.nav.origin; // This will be null on first load

// so in your component 

const Map = () => {
    const origin = useSelector(selectOrigin); // This initially will be null
// origin = null
  return (
    <MapView 
        style= {tw`flex-1`}
        mapType = "mutedStandard"
        initialRegion={{
            latitude: origin.location.latitude, // This is where you get the null reff -> null.location.latitude
            longitude: origin.location.longitude, 
            latitudeDelta: 0.005,
            longitudeDelta: 0.005,
          }}     

    />
  );
};

如果你使用的是TypeScript,我建议使用???操作符

  • ?安全导航算子
  • ??空合并运算符
origin?.location?.latitude ?? 0 //or the default that you need

相关问题