ArslArsl ArslArsl - 2 months ago 13
React JSX Question

setState in componentDidMount doesn't change state

I know there are plenty of questions about componentdidmount and setState insde of it. But I can't understand why my this.state.context is null when I console.log it?

Here is a fragment of my component. I draws some figures using canvas.

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();
},


At this point something strange:

console.log(this.state.context);


console.log will print null!!! But ctx is actually not null!!!

Answer

setState actions are batched, making them asynchronous. You can supply a function as a second argument which is called when setState is completed and your component has re-rendered. For more info, see: https://facebook.github.io/react/docs/component-api.html

This should work:

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