admin管理员组

文章数量:1379475

So, in my code looks like setData works fine and gives the fetched data to my state. However it doesn't work at fist render. But if I cahange something in the code website will be rendered again and country name is gonna show up on the screen just how I wanted.

But this error keeps popping up: Uncaught TypeError: Cannot read properties of undefined (reading 'mon')

import React, { useState, useEffect } from 'react';
import { useParams } from 'react-router-dom';

function Country() {
  const { countryName } = useParams();
  const [data, setData] = useState([]);
  const [country, setCountry] = useState({});

  useEffect(() => {
    fetch('.1/all')
      .then(resp => resp.json())
      .then(datas => setData(datas));
  }, [])

  useEffect(() => {
    setCountry(data.find(a => a.namemon.toLowerCase() == countryName.replaceAll("-", " ")));
  }, [data])

  return (
    <>
      {
        <h1>{country.namemon}</h1>
      }
    </>
  )
}

export default Country
<script src=".6.3/umd/react.production.min.js"></script>
<script src=".6.3/umd/react-dom.production.min.js"></script>

So, in my code looks like setData works fine and gives the fetched data to my state. However it doesn't work at fist render. But if I cahange something in the code website will be rendered again and country name is gonna show up on the screen just how I wanted.

But this error keeps popping up: Uncaught TypeError: Cannot read properties of undefined (reading 'mon')

import React, { useState, useEffect } from 'react';
import { useParams } from 'react-router-dom';

function Country() {
  const { countryName } = useParams();
  const [data, setData] = useState([]);
  const [country, setCountry] = useState({});

  useEffect(() => {
    fetch('https://restcountries./v3.1/all')
      .then(resp => resp.json())
      .then(datas => setData(datas));
  }, [])

  useEffect(() => {
    setCountry(data.find(a => a.name.mon.toLowerCase() == countryName.replaceAll("-", " ")));
  }, [data])

  return (
    <>
      {
        <h1>{country.name.mon}</h1>
      }
    </>
  )
}

export default Country
<script src="https://cdnjs.cloudflare./ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare./ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

Share Improve this question asked Aug 21, 2022 at 13:24 LshirocLshiroc 691 gold badge3 silver badges8 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 3

It means that country.name is undefined (and not an object with mon property).

On initial render country is {} (an empty object).

So, country.name returns undefined.

And undefined does not have mon property. Hence, the error.

So, a good rule of thumb before accessing a property would be to check if that property even exists.

<h1>{country?.name?.mon}</h1>

Most of the time, you don't want to display tags if there is no data.

So, you would like to do something like this.

Markup after && will be rendered only if expression before it, is truthy value.

{country?.name?.mon && (
 <h1>{country.name.mon}</h1>
)}

As country initial value is an empty object, the name property will be undefined, which causes this error, You just need to set an initial value for name too, as an empty object

const [country, setCountry] = useState({ name: {} });

Full example of code.

import React, { useState, useEffect } from 'react';
import { useParams } from 'react-router-dom';

function Country() {
  const { countryName } = useParams();
  const [data, setData] = useState([]);
  const [country, setCountry] = useState({ name: {} });

  useEffect(() => {
    fetch('https://restcountries./v3.1/all')
      .then(resp => resp.json())
      .then(datas => setData(datas));
  }, [])

  useEffect(() => {
    setCountry(data.find(a => a.name.mon.toLowerCase() == countryName.replaceAll("-", " ")));
  }, [data])

  return (
    <>
      {
        <h1>{country.name.mon}</h1>
      }
    </>
  )
}

export default Country

Or you can optionally chain the name property.

<h1>{country.name?.mon}</h1>

I opened a new tab in Chrome and paste your api https://restcountries./v3.1/all and from the network tab, the results have some strange objects which do not have "name": {"mon"....}

You have to filter these objects out

本文标签: javascriptReact error 39Cannot read properties of undefined (reading 39map39)39Stack Overflow