将对象添加到 useState() 并在本机反应中显示数据

add Object to useState() and show data in react native

我有以下功能:

const [dataLoc, setDataLoc] = useState({date: "No data received yet from sensor", coords: {}});

我这里设置的位置:

Geolocation.getCurrentPosition(
      location => {
        const date = dateToString(location.timestamp);
        const coords = location.coords
        setDataLoc({date, coords})
      }
)

坐标界面:

export interface GeoCoordinates {
    latitude: number;
    longitude: number;
    accuracy: number;
    altitude: number | null;
    heading: number | null;
    speed: number | null;
    altitudeAccuracy?: number | null;
}

发件人:

import Geolocation from 'react-native-geolocation-service';

我想这样渲染数据:

<Text style={styles.data}>{dataLoc.coords.latitude}</Text>

但我收到:

error: SyntaxError: .../App.tsx: Unexpected token

我无法收到该对象的任何属性,因为该对象是空的 {},就像我在 useState() 中所述。

当我尝试在 useState() 中定义对象时,出现错误,因为例如altitude 可以是 numbernull.

我的问题是如何在不定义 dataLoc 的情况下将坐标添加到 dataLoc,并且仍然检索对象元素或将其定义为某些值可以是数字或空值?

我也在useState()中尝试定义为:

const [dataLoc, setDataLoc] = useState({
date: "No data received yet from sensor", 
coords: { 
  latitude: 0,
  longitude: 0,
  altitude: 0,
  accuracy: 0,
  altitudeAccuracy: 0,
  heading: 0,
  speed: 0
}
});

但后来我收到:

Type '{ latitude: number; longitude: number; altitude: number 
| null; accuracy: number; altitudeAccuracy: number | null; 
heading: number | null; speed: number | null; }' is not 
assignable to type '{ latitude: number; longitude: number; 
altitude: number; accuracy: number; altitudeAccuracy: number; 
heading: number; speed: number; }'.
Types of property 'altitude' are incompatible.
Type 'number | null' is not assignable to type 'number'.
Type 'null' is not assignable to type 'number'.

您需要明确说明状态值的类型,因为无法从初始值推断出它。

例如,如果您的状态值为 number,则不需要类型注释。

const [value, setValue] = useState(0); // TypeScript infers the number type

setValue(53); // Ok
setValue('some string'); // Error

但假设您的值可以是 numberstring。 TS 不可能从初始值推断出这一点,因为一个值不能同时是 stringnumber。所以我们将类型传递给这个 generic useState 函数。

const [num, setNum] = useState(0); // TypeScript infers the number type
const [value, setValue] = useState<string | number>(0); // We explicitly pass string | number

setNum('some string'); // Error
setValue('some string'); // Ok

现在回到你的具体例子,当你像这样初始化你的状态时。

const [dataLoc, setDataLoc] = useState({
  date: "No data received yet from sensor", 
  coords: { 
    latitude: 0,
    longitude: 0,
    altitude: 0,
    accuracy: 0,
    altitudeAccuracy: 0,
    heading: 0,
    speed: 0
  }
});

如错误所示,这是TS从中推断出的类型

{
  date: string;
  coords: { 
    latitude: number;
    longitude: number;
    altitude: number;
    accuracy: number;
    altitudeAccuracy: number;
    heading: number;
    speed: number;
  };
}

但这并不代表现实,因此您需要定义类型或从库中获取类型并将其传递给 useState

interface DataLoc {
  date: string,
  coords: { 
    latitude: number;
    longitude: number;
    accuracy: number;
    altitude: number | null;
    heading: number | null;
    speed: number | null;
    altitudeAccuracy?: number | null;
  };
}

const [dataLoc, setDataLoc] = useState<DataLoc>({
  date: "No data received yet from sensor", 
  coords: { 
    latitude: 0,
    longitude: 0,
    altitude: 0,
    accuracy: 0,
    altitudeAccuracy: 0,
    heading: 0,
    speed: 0
  }
});

这应该可以解决错误。我建议从库中获取正确的类型,而不是像我在代码片段中那样复制它。

const [dataLoc, setDataLoc] = useState<{
  date: string;
  coords: GeoCoordinates;
}>({
  date: '', 
  coords: {} as GeoCoordinates,
});
/*
 * Your another codes
 */

//calling it everwhere you want (e.g in useEffect)
const _setLocation = () => {
  //checking location permission then
  Geolocation.getCurrentPosition(
    ({timestamp, coords}) => {
      const date = dateToString(timestamp);
      setDataLoc({date, coords});
    },
    e => console.log(e),
  );
};
/*
 * Your another codes
 */
return (
  <Text style={styles.data}>
    {dataLoc.coords?.latitude}
  </Text>
);