如何在onClick之前调用isActive func

时间:2017-09-18 14:32:32

标签: reactjs react-router

oddEvent = (match, location) => {
    if (!match) {
      return false
    } else {
      this.location = match.url
      return true
    }
  }

handleChange = (event) => {
    this.location === '/home' ? this.setState({isHome: true  })
                              : this.setState({isHome: false })
  }



<ul className="main-header__nav-list">
            {links.map((link, i) => {
              return (
                <li key={i}
                    className="main-header__nav-item">
                  <NavLink to={link.linkTo} 
                           activeClassName="main-header__nav-link--active" 
                           className="main-header__nav-link"
                           onClick={this.handleChange}
                           isActive={this.oddEvent}>
                           {link.text}
                  </NavLink>
                </li>
              )
            })}
          </ul>

想要在我的NavLink&#39; Home&#39;没有被选中。 oddEvent func给出当前位置。但onClick始终先行,然后handleChange取旧的死记硬背名称。我怎么能先打电话给isActive?或者我如何在onClick函数中获得新的路径?

1 个答案:

答案 0 :(得分:0)

'isActive'函数由react-router调用。我相信它没有为您正确更新。为此,请确保使用 withRouter 组件包装组件,并且父组件不会阻止重新呈现。你也可以在official doc中看到一个例子。

import { withRouter } from 'react-router'

class MainHeaderWithRouter extends Component {
    render() {
        <ul className="main-header__nav-list">
        {links.map((link, i) => {
          return (
            <li key={i}
                className="main-header__nav-item">
              <NavLink to={link.linkTo} 
                       activeClassName="main-header__nav-link--active" 
                       className="main-header__nav-link"
                       onClick={this.handleChange}
                       isActive={this.oddEvent}>
                       {link.text}
              </NavLink>
            </li>
          )
        })}
      </ul>  
    }    
}

const MainHeaderWithRouter = withRouter(ShowTheLocation)