简体   繁体   English

如何在反应中访问嵌套对象内的数据值

[英]How to access value of data inside nested object in react

I am new to react and having problem trying to access data inside of the nested object.我是新手,尝试访问嵌套对象内的数据时遇到问题。 I am trying to create a app where the condition checks todays date with the date of the list and if the condition is true it returns the list.我正在尝试创建一个应用程序,其中条件检查今天的日期和列表的日期,如果条件为真,则返回列表。

The list looks like this :该列表如下所示:


const data = [{
    id: 1,
    name : 'Ashley',
    birthday : {
      year : 1998,
      month: 5,
      date : 22,
    },
    img : 'img'
  },
  {
    id: 2,
    name : 'Bill',
    birthday : {
      year : 1993,
      month: 2,
      date : 12,
    },
    img : 'img'
  },
];

I have made a date object with which the comparision will be done.我制作了一个日期对象,用来进行比较。

const today = new Date();
const year = today.getFullYear();
const month = today.getMonth()+1;
const date = today.getDate();

In the list, the birthday contains three other values and i can not access them using 'filter' method.在列表中,生日包含其他三个值,我无法使用“过滤器”方法访问它们。

The rest of code are below :其余代码如下:

function App() {
  const [people, setPeople] = useState(data)
  return (
    <section className = 'container'>
      <h1>{List.length} birthdays today</h1>
    <List people= {people}/>
      <button className="btn" onClick ={() => { setPeople([])}}>Clear All</button>
    </section>
  )
}
const List = ({people}) =>{
  return (
    <>
     { data.filter((person) => {
       const {id, name, birthday, img} = person;
       const age = year-person.birthday.year;
      if(person.birthday.month === month && person.birthday.date === date){
        return(
         <article className= 'person' key = {id}>
            <h2>{name}</h2>
            <p>{age} years old</p>
            <img src = {img} alt = "person"></img>
         </article>
       )}
       return (
         []
       )
     })} 
    </>
  )
}

Sorry about the long description.抱歉,描述太长了。

The filter function takes a predicate as a parameter that returns true or false, then returns the elements for which the condition is true. filter函数将谓词作为返回 true 或 false 的参数,然后返回条件为 true 的元素。

You are returning JSX/an empty array in the predicate, so I am assuming what you want is to actually map the elements to JSX.您在谓词中返回 JSX/一个空数组,所以我假设您想要的是将元素实际map到 JSX。

Your code would be:您的代码将是:

const List = ({people}) =>{
  return (
    <>
      {people.map((person) => {
        const {id, name, birthday, img} = person;
        const age = year - birthday.year;
        if(birthday.month === month && birthday.date === date){
          return (
            <article className='person' key={id}>
                <h2>{name}</h2>
                <p>{age} years old</p>
                <img src={img} alt="person"></img>
            </article>
          )
        }
        return null;
      })} 
    </>
  )
}

I have replaced data by people as it is the correct prop, and [] by null as [] is not valid JSX.我已经people替换了data ,因为它是正确的道具, []替换为null因为[]不是有效的 JSX。

Alternatively, you can filter then map as follow:或者,您可以filter然后map如下:

const List = ({people}) =>{
  return (
    <>
      {people
        .filter((person) => person.birthday.month === month && person.birthday.date === date)
        .map((person) => {
          const {id, name, birthday, img} = person;
          const age = year - birthday.year;
          return (
            <article className='person' key={id}>
                <h2>{name}</h2>
                <p>{age} years old</p>
                <img src={img} alt="person"></img>
            </article>
          )
        })}
    </>
  )
}

You should be filtering based on the people being passed into List , not the data object.您应该根据传递给Listpeople而不是data对象进行过滤。

const List = ({people}) =>{
  return (
    <>
      // instead of data
      { people.filter((person) => {
        const {id, name, birthday, img} = person;
        ...

That will allow you to access id , name , birthday , and img这将允许您访问idnamebirthdayimg

You dont need filter on single object which is inside array您不需要对数组内的单个对象进行过滤

const data = [{
id: 1,
name : 'Ashley',
birthday : {
  year : 1998,
  month: 5,
  date : 22,
},
img : 'img'
}]

let birthdayYear = data[0].birthday.year
let birthdayMonth = data[0].birthday.month
let birthdayDay = data[0].birthday.date

You can access like this if you have single object only but if multiple then do this如果您只有单个对象,则可以这样访问,但如果有多个对象,则执行此操作

const data = [
{
    id: 1,
    name : 'Ashley',
    birthday : {
      year : 1998,
      month: 5,
      date : 22,
    },
    img : 'img'
    },
{
    id: 2,
    name : 'John',
    birthday : {
      year : 1993,
      month: 4,
      date : 12,
    },
    img : 'img'
    }
]

let myObject = data.find(element=> element.id === 2)
let birthdayYear = myObject.birthday.year
let birthdayMonth = myObject.birthday.month
let birthdayDay = myObject.birthday.date

let me know if you found this complex如果你发现这个复杂,请告诉我

You are passing props in curly brackets:您在大括号中传递道具:

<List people= {people}/>

it should be passed like this:它应该像这样传递:

<List people=people/>

and data.filter should be replaced with people.map .data.filter应该替换为people.map

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM