我对 ReactJS 很陌生(就像今天刚开始一样)。我不太明白如何setState工作。我正在结合 React 和 Easel JS 来根据用户输入绘制一个网格。这是我的 JS 箱:http: //jsbin.com/zatula/edit ?js,output
setState
这是代码:
var stage; var Grid = React.createClass({ getInitialState: function() { return { rows: 10, cols: 10 } }, componentDidMount: function () { this.drawGrid(); }, drawGrid: function() { stage = new createjs.Stage("canvas"); var rectangles = []; var rectangle; //Rows for (var x = 0; x < this.state.rows; x++) { // Columns for (var y = 0; y < this.state.cols; y++) { var color = "Green"; rectangle = new createjs.Shape(); rectangle.graphics.beginFill(color); rectangle.graphics.drawRect(0, 0, 32, 44); rectangle.x = x * 33; rectangle.y = y * 45; stage.addChild(rectangle); var id = rectangle.x + "_" + rectangle.y; rectangles[id] = rectangle; } } stage.update(); }, updateNumRows: function(event) { this.setState({ rows: event.target.value }); this.drawGrid(); }, updateNumCols: function(event) { this.setState({ cols: event.target.value }); this.drawGrid(); }, render: function() { return ( <div> <div className="canvas-wrapper"> <canvas id="canvas" width="400" height="500"></canvas> <p>Rows: { this.state.rows }</p> <p>Columns: {this.state.cols }</p> </div> <div className="array-form"> <form> <label>Number of Rows</label> <select id="numRows" value={this.state.rows} onChange={ this.updateNumRows }> <option value="1">1</option> <option value="2">2</option> <option value ="5">5</option> <option value="10">10</option> <option value="12">12</option> <option value="15">15</option> <option value="20">20</option> </select> <label>Number of Columns</label> <select id="numCols" value={this.state.cols} onChange={ this.updateNumCols }> <option value="1">1</option> <option value="2">2</option> <option value="5">5</option> <option value="10">10</option> <option value="12">12</option> <option value="15">15</option> <option value="20">20</option> </select> </form> </div> </div> ); } }); ReactDOM.render( <Grid />, document.getElementById("container") );
当您使用其中一个下拉菜单更改行数或列数时,您可以在 JSbin 中看到,第一次不会发生任何事情。下次更改下拉值时,网格将绘制到先前状态的行和列值。我猜这是因为我的this.drawGrid()函数在setState完成之前正在执行。也许还有其他原因?
this.drawGrid()
感谢您的时间和帮助!
setState(updater[, callback])是一个异步函数:
setState(updater[, callback])
https://facebook.github.io/react/docs/react- component.html#setstate
您可以在 setState 使用第二个参数完成后执行一个函数,callback例如:
callback
this.setState({ someState: obj }, () => { this.afterSetStateFinished(); });
React 功能组件中的钩子也可以这样做:
https://github.com/the-road-to-learn-react/use-state-with- callback#usage
看看 useStateWithCallbackLazy:
import { useStateWithCallbackLazy } from 'use-state-with-callback'; const [count, setCount] = useStateWithCallbackLazy(0); setCount(count + 1, () => { afterSetCountFinished(); });