2017-02-19 54 views
0

Im新手到React js,我不知道下面的代码有什么问题,但我得到setState不是函数错误。请帮我解决这个问题。Reactjs this.setState不是函数错误

class AppBarLayout extends React.Component { 
    constructor(props) { 
     super(props); 

     this.state = { 
     visibleSideBar:true, 
     slide:"" 
     } 
    } 
    showProfile(){ 

    this.setState({ 
     slide:'slide' 
    }); 
    console.log(this.state.slide); 
    } 
    render(){ 
    return(
      <div> 
     <header> 
      <NavBar show={this.showProfile}/> 
      <Profile slide={this.state.slide} /> 
     </header> 
     </div> 
    ); 
    } 
} 
export default AppBarLayout; 
+0

的可能的复制[无法访问阵营实例(本)事件处理程序内(http://stackoverflow.com/questions/29577977/unable-to-access-react- instance-this-inside-event-handler) –

回答

2

扩展在Delapouite“如果你不喜欢绑定构造函数中的每个函数,你可以使用箭头函数自动绑定到正确的上下文。

例如:

class AppBarLayout extends React.Component { 
    constructor(props) { 
     super(props); 

     this.state = { 
     visibleSideBar:true, 
     slide:"" 
     } 
    } 

    // Now showProfile is an arrow function 
    showProfile =() => { 
    this.setState({ 
     slide:'slide' 
    }); 
    console.log(this.state.slide); 
    } 

    render(){ 
    return(
     <div> 
     <header> 
      <NavBar show={this.showProfile}/> 
      <Profile slide={this.state.slide}/> 
     </header> 
     </div> 
    ); 
    } 
} 
export default AppBarLayout; 
+0

使用这个语法时要小心,它不是标准的(还),需要一个特定的Babel变换。 – Delapouite

+0

是的,虽然它[越来越] [http://caniuse.com/#search=arrow%20functions] –