reactjs - 如何访问 useEffect 中的 URL 参数?
问题描述
我有一个功能组件,我试图通过钩子访问已在 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 钩子,因为我只需要它们运行一次。
然后我使用 if 语句在调用“setLectures()”之前检查参数。有趣的是,当我setLectures()
在 if 语句(要 DRY)之前调用时,然后console.log
是参数。它返回了 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)
}
})
}, [])
推荐阅读
- python - 如何从通知中删除“python”标题?,我正在使用 plyer.notification.notify
- r - 根据列中的元素对 R 中的数据框进行子集化
- javascript - 如何修复对象数组中对象的属性?
- reactjs - 如何将回历添加到 FullCalendar
- r - 基于字符串匹配和分号分隔字段
- domain-driven-design - 事件风暴和读取事件
- javascript - mathjax-node 中的 Mhchem 无法正确呈现复杂的公式
- api - 即使从具有白名单 ip 的服务器也无法访问 sfc api
- apache-spark - 使用 pyspark 从 AWS Glue 中的 DataFrames 创建列表的最快方法
- css - 浏览器标头和操作系统标头的高度