我对ReactJS还是个新手(今天才开始)。我不太明白setState是如何工作的。我结合React和Easel JS根据用户输入绘制网格。这是我的JS bin: http://jsbin.com/zatula/edit?js,output

代码如下:

    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完成之前执行。也许还有别的原因?

谢谢你的时间和帮助!


当前回答

如果组件有变化,每次setState时都会调用render来重新渲染。如果您将对drawGrid的调用移到那里,而不是在update*方法中调用它,应该不会有问题。

如果这对您不起作用,还有一个setState的重载,它将回调作为第二个参数。作为最后的手段,你应该可以利用这一点。

其他回答

当接收到新的道具或状态时(就像你在这里调用setState), React会调用一些函数,它们被称为componentWillUpdate和componentDidUpdate

在你的例子中,只需添加一个componentDidUpdate函数来调用this.drawGrid()

这里是JS Bin中的工作代码

正如我提到的,在代码中,componentDidUpdate将在this.setState(…)之后被调用。

那么componentDidUpdate内部将调用this.drawGrid()

在React https://facebook.github.io/react/docs/component-specs.html#updating-componentwillupdate中阅读更多关于组件生命周期的信息

如果组件有变化,每次setState时都会调用render来重新渲染。如果您将对drawGrid的调用移到那里,而不是在update*方法中调用它,应该不会有问题。

如果这对您不起作用,还有一个setState的重载,它将回调作为第二个参数。作为最后的手段,你应该可以利用这一点。

当setState()方法以相同的值(与当前值)调用时,React.useEffect()钩子不会被调用。因此,作为一种变通方法,使用另一个状态变量手动重新触发回调。

注意:当你的回调正在解析一个承诺或其他东西时,你必须在状态更新后调用它(即使UI保持不变),这是有用的。

import * as React from "react";

const randomString = () => Math.random().toString(36).substr(2, 9);

const useStateWithCallbackLazy = (initialValue) => {
  const callbackRef = React.useRef(null);
  const [state, setState] = React.useState({
    value: initialValue,
    revision: randomString(),
  });

  /**
   *  React.useEffect() hook is not called when setState() method is invoked with same value(as the current one)
   *  Hence as a workaround, another state variable is used to manually retrigger the callback
   *  Note: This is useful when your callback is resolving a promise or something and you have to call it after the state update(even if UI stays the same)
   */
  React.useEffect(() => {
    if (callbackRef.current) {
      callbackRef.current(state.value);

      callbackRef.current = null;
    }
  }, [state.revision, state.value]);

  const setValueWithCallback = React.useCallback((newValue, callback) => {
    callbackRef.current = callback;

    return setState({
      value: newValue,
      // Note: even if newValue is same as the previous value, this random string will re-trigger useEffect()
      // This is intentional
      revision: randomString(),
    });
  }, []);

  return [state.value, setValueWithCallback];
};

用法:

const [count, setCount] = useStateWithCallbackLazy(0);

setCount(count + 1, () => {
   afterSetCountFinished();
});

在React 16.8以后的钩子中,使用useEffect很容易做到这一点

我创建了一个CodeSandbox来演示这一点。

useEffect(() => {
  // code to be run when state variables in
  // dependency array changes
}, [stateVariables, thatShould, triggerChange])

基本上,useEffect与状态变化同步,这可以用于渲染画布

import React, { useState, useEffect, useRef } from "react";
import { Stage, Shape } from "@createjs/easeljs";
import "./styles.css";

export default function App() {
  const [rows, setRows] = useState(10);
  const [columns, setColumns] = useState(10);
  let stage = useRef()

  useEffect(() => {
    stage.current = new Stage("canvas");
    var rectangles = [];
    var rectangle;
    //Rows
    for (var x = 0; x < rows; x++) {
      // Columns
      for (var y = 0; y < columns; y++) {
        var color = "Green";
        rectangle = new Shape();
        rectangle.graphics.beginFill(color);
        rectangle.graphics.drawRect(0, 0, 32, 44);
        rectangle.x = y * 33;
        rectangle.y = x * 45;

        stage.current.addChild(rectangle);

        var id = rectangle.x + "_" + rectangle.y;
        rectangles[id] = rectangle;
      }
    }
    stage.current.update();
  }, [rows, columns]);

  return (
    <div>
      <div className="canvas-wrapper">
        <canvas id="canvas" width="400" height="300"></canvas>
        <p>Rows: {rows}</p>
        <p>Columns: {columns}</p>
      </div>
      <div className="array-form">
        <form>
          <label>Number of Rows</label>
          <select
            id="numRows"
            value={rows}
            onChange={(e) => setRows(e.target.value)}
          >
            {getOptions()}
          </select>
          <label>Number of Columns</label>
          <select
            id="numCols"
            value={columns}
            onChange={(e) => setColumns(e.target.value)}
          >
            {getOptions()}
          </select>
        </form>
      </div>
    </div>
  );
}

const getOptions = () => {
  const options = [1, 2, 5, 10, 12, 15, 20];
  return (
    <>
      {options.map((option) => (
        <option key={option} value={option}>
          {option}
        </option>
      ))}
    </>
  );
};

setState(updater[, callback])是一个异步函数:

https://facebook.github.io/react/docs/react-component.html#setstate

你可以在setState结束后使用第二个参数回调来执行一个函数,比如:

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