React의 컴포넌트를 렌더링하기 위해 API에서 오는 데이터를 매핑할 수 없습니다.

1개월 전 질문 1개월 전 토론 34 views

axios.get가 리턴하는 각 위치에 대해 Leaflet Marker을 렌더링 하고 싶습니다. (각각의 위치가 있는 오브젝트 배열을 리턴)

여기서 두 가지 에러가 발생합니다.

"Uncaught TypeError: data.map is not a function"

"Warning: Can't perform a React state update on a component that hasn't mounted yet. This indicates that you have a side-effect in your render function that asynchronously later calls tries to update the component. Move this work to useEffect instead"

로컬 샘플로 하면 잘 되는데요.

문제는 그게 약속에서 검색된 데이터를 사용하게 만드는 것이라서요.

import { useState } from "react"
import { MapContainer, TileLayer, Marker, Popup } from 'react-leaflet'
import { Link } from "react-router-dom"
import axios from "axios"

import "../styles/Map.css"

export default function Map() {
    const [data, setData] = useState({})

    async function getData() {
        await axios.get("http://localhost:8080")
            .then(data => data.json())
            .then(data => setData(data))
            .catch(data => data = "")
    }

    getData()
    
    return (
        <main>
            <MapContainer center={[-23.6334841179179, -46.46843854558035]} zoom={13} scrollWheelZoom={true}>
                <TileLayer
                    attribution='&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
                    url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
                />
                <Marker position={[-23.6334841179179, -46.46843854558035]}>
                    <Popup>{"My house <3"}</Popup>
                </Marker>
                {
                    data && data.map(loc => (
                        <Marker key={data.id} position={[loc.latitude, loc.longitude]}>
                            <Popup>{loc.name}</Popup>
                        </Marker>
                    ))
                }
            </MapContainer>

            <button><Link to="/register">Register new Location</Link></button>
        </main>
    )

reactjs

2022-05-23 10:09

1개의 해답

data?.map을 이렇게 써보세요.

import { MapContainer, TileLayer, Marker, Popup } from 'react-leaflet'
import { Link } from "react-router-dom"
import axios from "axios"

import "../styles/Map.css"

export default function Map() {
    const [data, setData] = useState([])

    async function getData() {
        await axios.get("http://localhost:8080")
            .then(data => data.json())
            .then(data => setData(data))
            .catch(data => data = "")
    }

    useEffect(()=>{
       getData();
    },[])
    
    return (
        <main>
            <MapContainer center={[-23.6334841179179, -46.46843854558035]} zoom={13} scrollWheelZoom={true}>
                <TileLayer
                    attribution='&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
                    url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
                />
                <Marker position={[-23.6334841179179, -46.46843854558035]}>
                    <Popup>{"My house <3"}</Popup>
                </Marker>
                {
                    data?.map(loc => (
                        <Marker key={data.id} position={[loc.latitude, loc.longitude]}>
                            <Popup>{loc.name}</Popup>
                        </Marker>
                    ))
                }
            </MapContainer>

            <button><Link to="/register">Register new Location</Link></button>
        </main>
    )
}


2022-05-23 10:11

해결방법이나 팁을 알고 계신다면


© 2022 pinfo. All rights reserved.