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

时间:2017-02-08 22:38:27

标签: javascript reactjs ecmascript-6

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

我在return语句之前在componentDidMount()render()中尝试了此方法。 React一直告诉我this未定义。

反应/ SRC /页/ 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

1 个答案:

答案 0 :(得分:0)

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