繁体   English   中英

React,这在 render() 和 componentDidMount() 中是未定义的

[英]React, this is undefined in render() and in componentDidMount()

我正在用我的所有路线迭代一个字符串数组。 然后检查当前 window.location.href` 是否包含这些路由中的任何一个,如果包含,那么我将获取匹配的 ref 并添加一个类来更改 css。

我在返回语句之前在componentDidMount()render()尝试了这个方法。 React 一直告诉我this是未定义的。

反应/src/pages/nav.js

      render() {
        let allRoutes = [];
        this.props.route.childRoutes.forEach(route => {
          allRoutes.push(route.path)
        })
        const url = window.location.href;
        allRoutes.forEach(route => {
          if (url.includes(route)) {
            this.refs[route].classList.add('active')
          } else {
            this.refs.root.classList.add('active')
          }
        })

安慰

Uncaught TypeError: Cannot read property 'classList' of undefined
    at eval (eval at <anonymous> (http://localhost:3000/assets/bundle.self-952529963c9d96b227c46b5e763e815b470d4de62fa7b9b876d16aa3475efce8.js?body=1:3270:2), <anonymous>:50:29)
    at Array.forEach (native)
    at Nav.render (eval at <anonymous> (http://localhost:3000/assets/bundle.self-952529963c9d96b227c46b5e763e815b470d4de62fa7b9b876d16aa3475efce8.js?body=1:3270:2), <anonymous>:48:17)
    at eval (eval at <anonymous> (http://localhost:3000/assets/bundle.self-952529963c9d96b227c46b5e763e815b470d4de62fa7b9b876d16aa3475efce8.js?body=1:2538:2), <anonymous>:796:21)
    at measureLifeCyclePerf (eval at <anonymous> (http://localhost:3000/assets/bundle.self-952529963c9d96b227c46b5e763e815b470d4de62fa7b9b876d16aa3475efce8.js?body=1:2538:2), <anonymous>:75:12)
    at ReactCompositeComponentWrapper._renderValidatedComponentWithoutOwnerOrContext (eval at <anonymous> (http://localhost:3000/assets/bundle.self-952529963c9d96b227c46b5e763e815b470d4de62fa7b9b876d16aa3475efce8.js?body=1:2538:2), <anonymous>:795:25)
    at ReactCompositeComponentWrapper._renderValidatedComponent (eval at <anonymous> (http://localhost:3000/assets/bundle.self-952529963c9d96b227c46b5e763e815b470d4de62fa7b9b876d16aa3475efce8.js?body=1:2538:2), <anonymous>:822:32)
    at ReactCompositeComponentWrapper.performInitialMount (eval at <anonymous> (http://localhost:3000/assets/bundle.self-952529963c9d96b227c46b5e763e815b470d4de62fa7b9b876d16aa3475efce8.js?body=1:2538:2), <anonymous>:362:30)
    at ReactCompositeComponentWrapper.mountComponent (eval at <anonymous> (http://localhost:3000/assets/bundle.self-952529963c9d96b227c46b5e763e815b470d4de62fa7b9b876d16aa3475efce8.js?body=1:2538:2), <anonymous>:258:21)
    at Object.mountComponent (eval at <anonymous> (http://localhost:3000/assets/bundle.self-952529963c9d96b227c46b5e763e815b470d4de62fa7b9b876d16aa3475efce8.js?body=1:2178:2), <anonymous>:46:35)

如果我在条件中放置一个调试器

allRoutes.forEach(route => {
  if (url.includes(route)) {
    debugger

并检查this控制台,它返回undefined

通过将其分配给另一个变量,然后使用新创建的变量访问道具在渲染中工作

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM