2017-07-29 5 views
1

に反応する私はこのようなコンポーネントを反応させていますコンポーネント

import React, { Component } from 'react' 
import { Sidebar, Segment, Button, Menu, Image, Icon, Header } from 'semantic-ui-react' 

export default class Footer extends Component { 

    constructor(props) { 
     super(props) 
     this.state = { 
      visible: false 
     } 
     this.handleClick = this.handleClick.bind(this); 
     this.handleClick(); 
    } 


    handleClick() { 

     this.props.socket.on('connect', function() { 
      console.log("PRINT this.state.visible"); 
      console.log('Connected'); 
     }); 

     this.props.socket.on('disconnect', function() { 
      console.log('Disconnected'); 
     }); 
    } 

    render() { 
     return (
      <div className='create-task-section'> 
       "HELLO" 
      </div> 
     ) 
    } 
} 

私はのWebSocketのIOを使用しています。方法this.props.socket.onで私は

this.state = { visible: false }

を印刷したい。しかし、私は、この変数を印刷するとき、私はundifinedエラーを取得しています。 this.props.socket.onのような匿名メソッドでthis.stateの値を読み込み/変更/更新するにはどうすればよいですか?

ありがとうございました!

+0

あなたは 'handleClick'メソッドを' bind'するのではなく、無名関数をバインドしてはいけません。 – Bergi

+0

'console.log(" PRINT "、this.state.visible)' not 'console.log(" PRINT this.state.visible ")'を意味すると思いますか? – Bergi

答えて

2

バインド 'this'。状態変数の使用を変更する

this.props.socket.on('connect', function() { 
      console.log("PRINT this.state.visible"); 
      console.log('Connected'); 
     }.bind(this)); 

「this.setState({可視:偽})」という習慣仕事としてthis.state.visibleた状態を変異させることはありません。また、イベント処理は、ユーザがクリックするまで機能しないので、handleClickではなく、componentDidMountメソッドで行う必要があります。

+0

なぜあなたはes6 arrow関数を使う代わりに 'this'を関数にバインドしますか? –

+0

@MaximKuzmin 'this'をバインドする方法はたくさんあります。矢印機能も良いです。コンストラクタ内のバインドされた関数を初期化することも良いです。バインドにes7 "::"を使用することもできます。反応インスタンスメソッドを使用しても良いです。 –

-1

矢印機能(ES6)を使用してください。

this.props.socket.on('connect',() => { 
    console.log("PRINT this.state.visible"); 
    console.log('Connected'); 
}); 

あなた無名関数は、独自のコンテキストとこの場合thisを持っているので、あなたはこのようにそれを行う必要がありますが、それと呼ばれます。矢印関数は新しいコンテキストを作成しないため、thisはコンポーネントのthisとなります。

関連する問題