我有一个功能组件,试图通过钩子访问已在react-router中命名的URL参数。
useEffect(() => {
document.title = props.match.params.subject
UserServices.getSubject(props.match.params.subject)
.then(resp => {
if (resp.data.lectures !== undefined) {
setLectures(resp.data.lectures)
mountLecture(resp.data.lectures[0].title)
}
})
}, [])
useEffect(() => {
if(props.match.params.title) mountLecture(props.match.params.title)
else mountLecture(lectures[0].title)
}, [props.match.params])
但是,它总是告诉我can't read the property title of undefined
,即使它出现在控制台日志中。
因此,我决定合并useEffect挂钩,因为我只需要它们运行一次。
然后,在调用“ setLectures()”之前,我使用了if语句来检查参数。需要注意的是,当我setLectures()
在if语句(要进行DRY)调用之前,调用console.log
了params。它返回了UserServices响应数据中数组的最后一项。
useEffect(() => {
document.title = props.match.params.subject
UserServices.getSubject(props.match.params.subject)
.then(resp => {
console.log(props.match.params.title)
if (props.match.params.title !== undefined) {
setLectures(resp.data.lectures)
mountLecture(props.match.params.title)
console.log(1)
}
else {
setLectures(resp.data.lectures)
console.log(10)
mountLecture(resp.data.lectures[0].title)
}
})
}, [])
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句