首页 > 解决方案 > 如何访问 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,即使它出现在控制台日志中。

标签: reactjsreact-hooks

解决方案


所以我决定结合 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)
          }
      })
  }, [])

推荐阅读