componentDidMount中的setState不会改变状态

setState in componentDidMount doesn't change state

本文关键字:改变 状态 中的 setState componentDidMount      更新时间:2023-09-26

我知道里面有很多关于componentdidmount和setState的问题。但我不明白为什么我的this.state.context是空的,当我console.log它?

这是我的组件的一个片段。我用画布画了一些人物。

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将打印空!!但是ctx实际上不是空的!!

setState操作是批处理的,因此它们是异步的。您可以提供一个函数作为第二个参数,该函数将在setState完成并且组件重新渲染时调用。更多信息请参见:https://facebook.github.io/react/docs/component-api.html

这个应该可以工作:

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