React-TypeScript:类型“ {}”中缺少属性“ geo”,但是在类型“ IMapProps”中是必需的

I am practicing React-Typescript. In my React app, I fetched the data from json placeholder API and from that API I want to use the geo location's lat and lng and pass it to My Map component. In my Map component I used google-map-react. I successfully displayed the map. In my Map component, I made an interface prop which is like this:

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

If I made geo optional like geo?: The Map appeared but If made geo required I got error like this: Property 'geo' is missing in type '{}' but required in type 'IMapProps. Also, I don't know how to use the Props in TypeScript.

这是我的上级组件,在这里我获取了数据并计划传递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;
评论
et_qui
et_qui

If you set the geo mandatory, the child component requires the geo property with lat and long properties. So say, when the parent component has not finished the axios call, your parent state is initialized to [] and your i.address.geo is basically undefined and that raises the error.

解决方法:

  1. You can keep the geo optional in child component.
  2. Or, you can have an initial geo type value in your parent state. i.e.
const [state, setState] = useState<any>({'address': {'geo': {
        lat: 60.1098678,
        lng: 24.7385084
      }}})

点赞
评论