this.state在函数内部未定义 - React JS

时间:2017-11-29 06:51:57

标签: reactjs ecmascript-6

为什么我的状态未定义?我尝试了各种解决方案,但没有一个适合我。有人可以指出这里做错了吗

编辑:

完整的组件代码

  class Sidebar extends React.Component {
    constructor (props) {
      super(props)
      this.state = {
        menuSelected: menuOptions.menuItems[0].title,
      }
      this.createMenuListItem = this.createMenuListItem.bind(this)
    }
    render () {
      console.log(this.state.menuSelected)
      function getChildItems (child) {
        let childItems = child.children.map(function (menuItem, index) {
          return createMenuListItem(menuItem)
        })
        return (
          <li key={child.title} className='dropdown'>
            <i className={child.iconName} />
            <span className='dropdown-toggle'>{child.title}</span>
            <ul className=''>
              {childItems}
            </ul>
          </li>
        )
      }
      function createMenuListItem (menuItem) {
        if (menuItem.hasChild === 'N') {
          console.log(this.state.menuSelected)
          return (
            <li key={menuItem.title}>
              <a href='#'>
                <i className={menuItem.iconName} />
                <span>{menuItem.title}</span>
              </a>
            </li>
          )
        } else {
          return getChildItems(menuItem)
        }
      }

      let menuItemsLoaded = menuOptions.menuItems.map((menuItem, index) => {
        return createMenuListItem(menuItem)
      })
      return (
        <nav id='sidebar'>
          <ul className='list-unstyled'>
            {menuItemsLoaded}
          </ul>
        </nav>
      )
    }
  }

  export default Sidebar

当从服务器动态加载侧边栏内容时,也可以建议更好的选项

1 个答案:

答案 0 :(得分:9)

使用function会丢失上下文,this不是您期望的那种。

在这种情况下,使用箭头功能:

render() {
  createMenuItems = (items) => {
    console.log(this.state.menuSelected)
    ...
  }
}

或者,以及我的建议,在createMenuItems方法之外移动render

createMenuItems = (items) => {
  console.log(this.state.menuSelected)
}

render() {
  return (
    <nav id='sidebar'>
      <ul className='list-unstyled'>
        {menumenuOptions.menuItems.map((menuItem, index) =>
          this.createMenuListItem(menuItem)
        )}
      </ul>
    </nav>
  )
}

在构造函数中绑定它也是可能的:

class YourComponent extends React.Component {
  constructor(props) {
    super(props)

    this.state = {
      menuSelected: '',
    }

    this.createMenuListItem = this.createMenuListItem.bind(this)
  }

  createMenuListItem() {
    console.log(this.state.menuSelected)
  }

  render() {
    return (
      <nav id='sidebar'>
        <ul className='list-unstyled'>
          {menumenuOptions.menuItems.map((menuItem, index) =>
            this.createMenuListItem(menuItem)
          )}
        </ul>
      </nav>
    )
  }
}