2016-09-21 3 views
0

나는 componentdidmount 및 setState insde에 대해 많은 의문점이 있음을 알고 있습니다. 하지만 왜 내가 this.state.context null 때 console.log 그것을 이해할 수 없다?componentDidMount의 setState가 상태를 변경하지 않음

다음은 제 구성 요소의 일부입니다. 나는 캔버스를 사용하여 몇 가지 그림을 그린다. 이상이 시점 뭔가

var App = React.createClass({  
     getInitialState(){ 
      var board = []; 
      for(var i=0; i<30; i++){ 
       var temp=[]; 
       for(var j=0; j<50; j++){ 
       temp.push(0); 
       } 
       board.push(temp); 
      }  
      //glider pattern 
      board[0][2]=1; 
      board[1][0]=1; 
      board[1][1]=1; 
      board[2][1]=1; 
      board[2][2]=1;  

      return { 
       width: 550, 
       height: 350, 
       step: 0, 
       board: board, 
       isOn: true, 
       isPaused: false, 
       context: null 
      } 
     }, 

     componentDidMount(){   
      var canvas = document.getElementById("canvas"); 
      var ctx = canvas.getContext("2d");    
      //drawing text 
      ctx.fillStyle = "#777"; 
      ctx.font = "16px arial"; 
      ctx.fillText("Yonger", 25, 343); 
      ctx.fillText("Older", 120, 343); 
      ctx.fillText("Generation:", 25, 18); 
      ctx.fillStyle = "rgb(140, 198, 101)"; 
      ctx.fillRect (85, 333, 10, 10);     
      ctx.fillStyle = "rgb(30, 104, 35)"; 
      ctx.fillRect (100, 333, 10, 10);     



      this.setState({context:ctx});   
      console.log(this.state.context); 
      this.draw();  
     }, 

:

  console.log(this.state.context); 

을 console.log가 null 인쇄됩니다! 하지만 ctx 실제로 null이 아닙니다!

+1

내가 여기 대답 http://stackoverflow.com/questions/39531547/issue-with-setstate-in-if-statement/39531639을 # 39531639 – StateLess

답변

3

setState 작업이 일괄 처리되어 비동기가됩니다. setState이 완료되고 구성 요소가 다시 렌더링 될 때 호출되는 두 번째 인수로 함수를 제공 할 수 있습니다. 더 많은 정보를 원하시면 다음을 참조하십시오 https://facebook.github.io/react/docs/component-api.html

이 작동합니다 :

this.setState({context:ctx},() => { 
    console.log(this.state.context); 
});   
관련 문제