【问题标题】:How to access URL params in useEffect?如何访问 useEffect 中的 URL 参数?
【发布时间】:2021-01-11 17:15:20
【问题描述】:

我有一个功能组件,我试图通过钩子访问在 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,即使它出现在控制台日志中。

【问题讨论】:

  • 你能控制台记录你的道具和讲座吗?
  • 我使用了 2 个 useEffecthooks,让我上传第二个,让你看看它是如何更新的。

标签: reactjs react-hooks


【解决方案1】:

所以我决定结合 useEffect 钩子,因为我只需要它们运行一次。

然后我使用 if 语句在调用“setLectures()”之前检查参数。需要注意的一点是,当我在 if 语句(要 DRY)之前调用 setLectures() 时,然后是 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)
          }
      })
  }, [])

【讨论】:

    猜你喜欢
    • 2015-04-27
    • 1970-01-01
    • 1970-01-01
    • 2019-09-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-29
    • 2020-05-30
    相关资源
    最近更新 更多