2016-03-04 67 views
0

我的組件內部值this.state始終爲空。下面是代碼:ReactJS this.state爲空

class Sidebar extends Component { 
    static propTypes = { 
    static: PropTypes.bool 
    }; 

    constructor(props) { 
    super(props); 

    this.state = { 
     static: false 
    }; 
    } 

    componentWillReceiveProps() { 
    console.log(this.state); 
    } 

    onMouseEnter() { 
    console.log(this.state); 
    } 

    onMouseLeave() { 
    console.log(this.state); 
    } 

    render() { 
    return (
     <nav className={s.root} onMouseEnter={this.onMouseEnter.bind(this)} onMouseLeave={this.onMouseLeave.bind(this)}> 

     </nav> 
    ); 
    } 
} 

在控制檯我只看到null鼠標輸入,鼠標離開和接受新道具。

你有什麼想法爲什麼會發生?

謝謝!

+0

適合我。你確定這是涉及這個問題的_only_代碼嗎? –

+0

嘗試從您的代碼中刪除靜態propTypes ... – yuyokk

+0

無法複製:https://jsbin.com/vurimac/edit?html,js,console,output。你的代碼在其他地方几乎肯定會發生另一個錯誤。 – rossipedia

回答

-2

如果您想設置初始狀態,則需要在構造函數中實現getInitialState(),而不是嘗試。

另外,在狀態上設置屬性的正確方法是使用setState({ static: false })而不是this.state.static = false

+0

不使用ES6語法時爲true,但在使用ES6時,不會調用setInitialState()。請參閱https://facebook.github.io/react/docs/react-component.html#constructor – Ficertyn

1

我只需要解決這個問題,發現問題是你需要將你的方法綁定到對象。我在構造函數中做了這個,它解決了我的問題。

class Sidebar extends Component { 
    static propTypes = { 
     static: PropTypes.bool 
    }; 

    constructor(props) { 
     super(props); 

     this.state = { 
      static: false 
     }; 

     this.onMouseEnter = this.onMouseEnter.bind(this); 
     this.onMouseLeave = this.onMouseLeave.bind(this); 
    } 

    componentWillReceiveProps() { 
     console.log(this.state); 
    } 

    onMouseEnter() { 
     console.log(this.state); 
    } 

    onMouseLeave() { 
     console.log(this.state); 
    } 

    render() { 
     return (
      <nav className={s.root} onMouseEnter={this.onMouseEnter} onMouseLeave={this.onMouseLeave}></nav> 
     ); 
    } 
} 
+0

OP在'onMouseEnter'和'onMouseLeave'屬性中調用'bind',這也應該起作用。 –

+0

@Zach我看到發生了這種情況,但認爲可能需要在構造函數中完成它,而不是在渲染函數中完成。 – Ficertyn