我是新的反应和有问题,试图访问数据内嵌套的对象。我正在尝试创建一个应用程序,其中条件检查今天的日期与列表的日期,如果条件为真,则返回列表。
列表如下:
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'
},
];
我已经创建了一个日期对象,将与之进行比较。
const today = new Date();
const year = today.getFullYear();
const month = today.getMonth()+1;
const date = today.getDate();
在列表中,生日包含另外三个值,我不能使用'filter'方法访问它们。
其余代码如下:
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 (
[]
)
})}
</>
)
}
抱歉,描述太长了。
filter
函数接受一个谓词作为返回真或假的参数,然后返回条件为真的元素。
您在谓词中返回JSX/空数组,因此我假设您想要的是实际将元素map
到JSX。
你的代码应该是:
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;
})}
</>
)
}
我将data
替换为people
,因为它是正确的prop,[]
替换为null
,因为[]
是无效的JSX。
或者,您可以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>
)
})}
</>
)
}
您应该基于传入List
的people
进行过滤,而不是data
对象。
const List = ({people}) =>{
return (
<>
// instead of data
{ people.filter((person) => {
const {id, name, birthday, img} = person;
...
允许您访问id
,name
,birthday
和img
不需要对数组内的单个对象进行筛选
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
如果只有一个对象,可以这样访问如果有多个对象,就这样访问
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
让我知道如果你发现这个复杂
你正在用大括号传递道具:
<List people= {people}/>
应该像这样传递:
<List people=people/>
和data.filter
应替换为people.map
。