如何访问useEffect中的URL参数?

Beulah Akindele

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

Beulah Akindele

因此,我决定合并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] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

如何从cakephp 2.9.7中的url访问参数

如何从BasePermission中访问URL参数?

如何从控制器中的URL访问参数值?

如何访问Meteor帮助器函数中的URL参数?

如何从Meteor中的模板文件访问URL参数?

在XSL中访问URL参数

在 JS (React) 中访问 URL 中的参数

如何访问参数化版本中的参数?

如何从状态组件访问ui-router中的参数(非URL和url)?

如何从 Azure DevOps 扩展访问 URL 参数

在Sails操作中访问url参数

如何在v-router中的beforeEach块中访问URL参数?

如何在 useEffect 的清理函数中访问 state/redux 存储?

如何从子组件中访问 react-router-redux URL 参数?

如何获取带有参数的Url路径以匹配它以检查Angular4 +中的访问权限?

如何使用Django REST Framework访问权限中的命名url参数?

React.js 如何从函数组件访问路由器链接 URL 中的参数?

如何在预加载功能之外的sapper中访问URL参数?

如何忽略URL中的参数?

如何通过url作为查询参数传递多维数组?并在laravel 6.0中访问这些参数

如何在useEffect中访问状态而无需重新触发useEffect?

ReactRouter:如何访问组件中的路由参数

如何在 EL 中访问请求参数

如何在Swift中访问程序参数?

如何访问函数中的命名参数?

如何从 Rails 中的 json API 访问参数?

如何访问HttpServletRequest中的POST参数?

如何访问方法中的匿名参数?

如何在 ActivityDesigner 中访问活动参数?