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

其他回答

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

我必须在更新状态后运行一些函数,而不是在每次更新状态时运行。 我的情况:

const [state, setState] = useState({
        matrix: Array(9).fill(null),
        xIsNext: true,
    });

...
...

setState({
    matrix: squares,
    xIsNext: !state.xIsNext,
})
sendUpdatedStateToServer(state);

这里sendUpdatedStateToServer()是更新状态后必须运行的函数。 我不想使用useEffect(),因为我不想在每个状态更新后运行sendUpdatedStateToServer()。

对我有用的是:

const [state, setState] = useState({
        matrix: Array(9).fill(null),
        xIsNext: true,
    });

...
...
const newObj = {
    matrix: squares,
    xIsNext: !state.xIsNext,
}
setState(newObj);
sendUpdatedStateToServer(newObj);

我只是创建了一个新对象,它是函数在状态更新后运行所需的,并简单地使用它。在这里,setState函数将继续更新状态,sendUpdatedStateToServer()将接收更新后的状态,这就是我想要的。

在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返回一个Promise

除了将回调函数传递给setState()方法外,你还可以将它包裹在一个异步函数周围,并使用then()方法——在某些情况下,这可能会产生更清晰的代码:

(async () => new Promise(resolve => this.setState({dummy: true}), resolve)()
    .then(() => { console.log('state:', this.state) });

在这里,你可以更进一步,创建一个可重用的setState函数,在我看来,它比上面的版本更好:

const promiseState = async state =>
    new Promise(resolve => this.setState(state, resolve));

promiseState({...})
    .then(() => promiseState({...})
    .then(() => {
        ...  // other code
        return promiseState({...});
    })
    .then(() => {...});

这在React 16.4中工作得很好,但我还没有在React的早期版本中测试它。

另外值得一提的是,将回调代码保存在componentDidUpdate方法中是大多数情况下(可能是所有情况下)更好的实践。

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