【发布时间】:2020-05-14 07:10:29
【问题描述】:
我正在我的对象中搜索一个数组,以使用过滤器和包含返回一个仅在我的类别数组中具有匹配值的对象。出于某种原因,每当我尝试运行我的函数时,都会不断得到
TypeError: 无法读取 null 的属性“包含”
或
TypeError: false 不是函数
如果我在过滤器中使用查找功能。
我做错了什么?
[{
"entryTitle": "What Is Sports Medicine Acupuncture?",
"date": "September 30 2015",
"categories": ["Knee Pain"],
"type": false
}, {
"entryTitle": "Providing Quality Care During The COVID-19 Pandemic",
"date": "March 23 2020",
"categories": null,
"type": false
}, {
"entryTitle": "Correcting Severe Antalgic Posture & Gait",
"date": "May 09 2020",
"categories": ["Back Pain"],
"type": true
}, {
"entryTitle": "The Successful Treatment Of Sciatica And Low Back Pain With Sports Medicine Acupuncture®",
"date": "July 24 2020",
"categories": ["Back Pain"],
"type": true
}, {
"entryTitle": "Treating A Quad Strain For A Super Heavyweight Powerlifter Before The KERN US Open Powerlifting Meet",
"date": "June 28 2018",
"categories": ["Knee Pain"],
"type": true
}, {
"entryTitle": "Treating A High Hamstring Strain Before A Powerlifting Competition Using Sports Medicine Acupuncture®",
"date": "June 05 2020",
"categories": ["Back Pain"],
"type": true
}, {
"entryTitle": "Free Acupuncture Treatments For Veterans Through The Veterans Choice Program",
"date": "June 08 2017",
"categories": ["Back Pain", "Disc Herniation", "Shoulder Pain"],
"type": true
}, {
"entryTitle": "The Treatment Of Whiplash Related Injuries With Acupuncture",
"date": "March 04 2016",
"categories": ["Disc Herniation"],
"type": false
}]
我的功能
const [selected, setSelected] = useState("all")
const [posts, setPosts] = useState(postData)
const filterPosts = value => {
let posts = postData
if (value !== "all") {
posts = postData.filter(post => post.categories.includes(value))
//posts = postData.filter(post => post.categories.find(post.categories === value))
}
setSelected(value)
setPosts(posts)
}
预期结果
{
"entryTitle": "What Is Sports Medicine Acupuncture?",
"date": "September 30 2015",
"categories": ["Knee Pain"],
"type": false
},
{
"entryTitle": "Treating A Quad Strain For A Super Heavyweight Powerlifter Before The KERN US Open Powerlifting Meet",
"date": "June 28 2018",
"categories": ["Knee Pain"],
"type": true
},
【问题讨论】:
-
"categories": null的情况下会出现此错误。因此,在尝试调用.includes(...)之前,您需要先确保您的categories不是null/undefined。
标签: javascript reactjs