将对象添加到 useState() 并在 React Native 中显示数据

发布于 2025-01-11 02:16:50 字数 2022 浏览 0 评论 0原文

我有以下功能:

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 中,并且仍然检索对象元素或定义某些值可以是数字或 null?

我还尝试在 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'.

I have the following function:

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

I set the location here:

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

With coords interface:

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

From:

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

I want to render the data like this:

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

But I receive:

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

I can't receive any properties of the object because the object is empty {} like I stated in useState().

When I try to define the object in useState() I get an error because e.g. altitude can be a number or null.

My question is how can I add coords to dataLoc without defining it and still retrieving the object elements or defining it that some values can be a number or null?

I also tried to define it in useState() as:

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
}
});

But then I receive:

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'.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

〃安静 2025-01-18 02:16:50
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>
);
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>
);
來不及說愛妳 2025-01-18 02:16:50

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

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

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

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

但假设您的值可以是数字字符串。 TS 不可能从 init 值推断出这一点,因为一个值不能同时是字符串数字。因此,我们将类型传递给这个 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
  }
});

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

You need to be explicit about the type of your state value because it can't be inferred from the init value.

For example if your state value is a number type annotation is not required.

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

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

But let't say your value can be either a number or a string. It's impossible for TS to infer that from the init value because a value can't be simultaneously a string and a number. So we we pass the type to this generic useState function.

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

Now going back to your specific example, when you initialize your state like this.

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
  }
});

as shown in the error, this is the type that TS infers from that

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

but that doesn't represent the reality, so you'd need to define the type or get it from the library and pass it to 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
  }
});

That should solve the error. I'd recommend getting the correct type from the library instead of duplicating it as I did in the code snippet.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文