英文:
React Loop over array within object
问题
以下是翻译好的内容:
考虑以下JSON:
const JSON = [
{
"Name": "Ben Davies",
"JobsList": [
{
"Company": "Company1",
"Date": "01/01/01",
},
{
"Company": "Company2",
"Date": "01/01/01",
},
{
"Company": "Company3",
"Date": "01/01/01",
}
]
}
]
我想将"Jobs"传递到页面上的新组件中,如下所示:
const [jobs] = useState(JSON);
return (
<CareerList
jobs={jobs}
/>
);
现在,在CareerList组件上,如果我检查jobs属性的长度,我只得到1,我理解这是因为我没有遍历数组,那么如何遍历数组呢?如何使长度在这种情况下为所期望的3?
const CareerList = (props) => {
const allJobs = props.jobs;
console.log(allJobs.length);
}
提前感谢。
英文:
Consider the following JSON:
const JSON = [
{
"Name":"Ben Davies",
"JobsList":[
{
"Company":"Company1",
"Date":"01/01/01",
},
{
"Company":"Company2",
"Date":"01/01/01",
},
{
"Company":"Company3",
"Date":"01/01/01",
}
]
}
]
I want to pass the "Jobs" into a new component on the page, like so:
const [jobs] = useState(JSON);
return(
<CareerList
jobs={jobs}
/>
);
Now on the CareerList component, if I check the length of the jobs prop, I only get 1, I understand that this is because I'm not looping through the array, so how do I loop through the array? How do I make the length the desired 3 in this case.
const CareerList = (props) => {
const allJobs = props.jobs;
console.log(allJobs.length)
}
Thanks in advance.
答案1
得分: 0
如果你只想要JobsList,那么可以将它传递给useState,如下所示:
const JSON = [
{
"Name": "Ben Davies",
"JobsList":[
{
"Company":"Company1",
"Date":"01/01/01",
},
{
"Company":"Company2",
"Date":"01/01/01",
},
{
"Company":"Company3",
"Date":"01/01/01",
}
]
}
]
const JobsList = JSON[0].JobsList
const [jobs, setJobs] = useState(JobsList);
尽管我建议您不要将JobsList重命名为jobs,保持名称不变会更好。
英文:
If you only want the JobsList then just pass that to the useState as follows:
const JSON = [
{
"Name":"Ben Davies",
"JobsList":[
{
"Company":"Company1",
"Date":"01/01/01",
},
{
"Company":"Company2",
"Date":"01/01/01",
},
{
"Company":"Company3",
"Date":"01/01/01",
}
]
}
]
const JobsList = JSON[0].JobsList
const [jobs, setJobs] = useState(JobsList);
Although I would recommend that you do not rename JobsList to jobs. Just keep it the same name.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论