Reaction返回&Quot;无法读取未定义的属性&Quot;Name"。"(Fetch API) [英] React returns "Cannot read property "name" of undefined." (Fetch API)

查看:41
本文介绍了Reaction返回&Quot;无法读取未定义的属性&Quot;Name"。"(Fetch API)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在尝试构建一个Reaction应用程序,该应用程序使用FETCH从API获取随机人物数据集。 尝试输出数据时,10次中有7次返回&Quot;TypeError:无法读取未定义&Quot;的属性‘name’。 不知何故(我猜是因为严格模式)-该函数总是被调用两次。 第一次它几乎总是返回UNDEFINED,我想这是在搞砸这个过程。

在所有与编码相关的事情上,我都是新手,所以我很想知道如何找出问题所在,以及我能做些什么来解决它。

function App() {
  const url = "https://randomuser.me/api/";

  const [person, setPerson] = useState();

  const getPerson = async () => {
    const response = await fetch(url);
    const data = await response.json();
    const person = data.results[0];
    const { title, first, last } = person.name;
    const { age, date } = person.dob;
    const { country, city, postcode } = person.location;
    const { name, number } = person.location.street;
    const { phone, email } = person;

    const newPerson = {
      name: title + " " + first + " " + last,
      dob: age + ", " + date,
      street: name + number,
      location: city + " " + postcode,
      country: country,
      phone: phone,
      email: email,
      picture: person.picture.large,
    };

    setPerson(newPerson);
  };

  useEffect(() => {
    getPerson();
  }, []);

  return (
    <Container>
      <Header />
      <Main>
        <Card>
          <CardHeader />
          <CardInnerContainer data={person} />
          <CardFooter />
        </Card>
      </Main>
      <Footer />
    </Container>
  );
}

export default App;
const CardInnerContainer = (props) => {

  return (
    <div className="card-inner-container">
      <div className="card-applicant-container">
        <p className="name">{props.person.name}</p>
        <p className="dob-age">{props.person.dob}</p>
        <p className="street">{props.person.street}</p>
        <p className="location">{props.person.location}</p>
        <p className="country">{props.person.country}</p>
        <p className="phone">{props.person.phone}</p>
        <p className="email">{props.person.email}</p>
      </div>
    </div>
  );
};

export default CardInnerContainer;

错误消息:

TypeError: Cannot read property 'name' of undefined
CardInnerContainer

   4 | return (
   5 |   <div className="card-inner-container">
   6 |     <div className="card-applicant-container">
>  7 |       <p className="name">{props.person.name}</p>
     | ^   8 |       <p className="dob-age">{props.person.dob}</p>
   9 |       <p className="street">{props.person.street}</p>
  10 |       <p className="location">{props.person.location}</p>

推荐答案

您需要有条件地呈现以Person为道具的组件。

       { person && <CardInnerContainer data={person} /> }

像这样。因此可以在获取并设置人员后呈现。

这篇关于Reaction返回&Quot;无法读取未定义的属性&Quot;Name&quot;。&quot;(Fetch API)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆