Can I execute a function after setState is finished updating?

前端 未结 5 1728
温柔的废话
温柔的废话 2020-11-30 17:32

I am very new to ReactJS (as in, just started today). I don\'t quite understand how setState works. I am combining React and Easel JS to draw a grid based on

5条回答
  •  再見小時候
    2020-11-30 18:08

    With hooks in React 16.8 onward, it's easy to do this with useEffect

    I've created a CodeSandbox to demonstrate this.

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

    Basically, useEffect synchronises with state changes and this can be used to render the canvas

    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 (
        

    Rows: {rows}

    Columns: {columns}

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

提交回复
热议问题