1

我正在练习 React-Typescript。在我的 React 应用程序中,我从json 占位符 API获取数据,并且从该 API 中我想使用地理位置的 lat 和 lng 并将其传递给 My Map 组件。在我的地图组件中,我使用了google-map-react。我成功地显示了地图。在我的地图组件中,我制作了一个界面道具,如下所示:

export interface IMapProps {
  geo: {
    lat: number;
    lng: number;
  }
}

如果我将地理设为可选,如geo?:地图出现,但如果需要地理,我会收到如下错误:Property 'geo' is missing in type '{}' but required in type 'IMapProps。另外,我不知道如何在 TypeScript 中使用 Props。

这是我获取数据并计划传递 Map 组件的父组件。

import React, { useEffect, useState } from 'react';
import Map from './Map'
export interface Data {
  id: number;
  name: string;
  username: string;
  email: string;
  address: {
    street: string;
    suite: string;
    city: string;
    zipcode: number;
    geo: {
      lat: number;
      lng: number;
    };
  };
  phone: number;
  website: string;
  company: {
    name: string;
    catchPhrase: string;
    bs: string;
  };
};

const Parent = () => {
  const [state, setState] = useState<Data[]>([])
  useEffect(() => {
    getData()
  }, [])
  const getData = async () => {
    const response = await fetch("https://jsonplaceholder.typicode.com/users");
    const data = await response.json();
    console.log(data);
    setState(data);
  };

  return (
    <div>
      {state.map(i => <Map geo={i.address.geo} />)} //IN HERE I am passing the props to the Map component. But after that I don't know how to use to porps in TypeScript

    </div>
  )
}



export default Parent

这是我想使用我的道具的我的地图组件。

import React, { useState } from 'react';
import GoogleMapReact from 'google-map-react';
import Marker from './Marker'
export interface IMapProps {
  geo: {
    lat: number;
    lng: number;
  }
}

const Maps = ({ geo }: IMapProps) => {

  const [state, setstate] = useState(
    {
      center: {
        lat: 60.1098678,
        lng: 24.7385084
      },
      zoom: 7
    }
  )

  return (

    <div >
      <div style={{ height: '100vh', width: '100%' }}>
        <GoogleMapReact
          bootstrapURLKeys={{ key: "**********" }}
          defaultCenter={state.center}
          defaultZoom={state.zoom}
        >
          <Marker
            lat={state.center.lat}
            lng={state.center.lng}
            text="My Marker" />
        </GoogleMapReact>
      </div>
    </div>


  );
};



export default Maps;
4

1 回答 1

0

如果设置为geo强制,则子组件需要geo具有 lat 和 long 属性的属性。也就是说,当父组件尚未完成 axios 调用时,您的父组件state被初始化为[]并且您i.address.geo的基本上是未定义的,这会引发错误。

修复方法:

  1. 您可以将geo可选项保留在子组件中。
  2. geo或者,您可以在 parent中有一个初始类型值state。IE
const [state, setState] = useState<any>({'address': {'geo': {
        lat: 60.1098678,
        lng: 24.7385084
      }}})

于 2020-05-09T06:42:41.390 回答