为什么 this.setState 对我有效

Why does this.setState work in my case

我只是想创建一个非常简单的应用程序,我将输入一个数字,然后计算机将生成具有该数字的框,并一次随机更改一个框的颜色。代码有效,但我不明白为什么它有效,在 randomBlinking 函数中,我只需要 this.setState({}) 或更奇怪的是,我可以在 this.setState( {}) 并且代码将工作相同,它会每 1 秒改变一个随机框的颜色。我把我的应用程序缩减到我不明白的部分,有人可以帮我回答这个问题吗?

import React from 'react';
import CubeRender from '../therapeuticEffect/CubeRender';
import '../therapeuticEffect/style.css';

class TherapeuticEffect extends React.Component {
constructor(props) {
    super(props)
    this.state = {
        cubeArray: [],
        cubeNumber: 0,
        cubeSize: 100,
    }
    this.blinking = null;
}

onNumberChange = (event) => {
    this.setState({ [event.target.name]: event.target.value })
}

onFormSubmit = (event) => {
    event.preventDefault();
    clearInterval(this.blinking);
    this.cubeArrayRender();
}

cubeArrayRender = () => {
    let { cubeNumber } = this.state;

    let cubes = parseInt(cubeNumber, 10);

    let array = cubes ? Array(cubes).fill() : [];
    let cubeArray = array.length === 0 ? [] : array.map((c) => (this.randomColor()));
    this.setState({ cubeArray })
    this.randomBlinking();
}

randomBlinking = () => {
    this.blinking = setInterval(() => {
        const array = this.state.cubeArray;
            const randIndex = Math.floor(Math.random() * array.length);
            array[randIndex] = this.randomColor();

            //HOW COULD THIS WORK

            this.setState({})
    }, 500);
}

randomColor = () => {
    let r = Math.floor(Math.random() * 256);
    let g = Math.floor(Math.random() * 256);
    let b = Math.floor(Math.random() * 256);
    let color = `rgb(${r}, ${g}, ${b})`
    return color;
}

render() {
    const { cubeArray, cubeNumber, cubeSize } = this.state
    return (
        <div>
            <form className='menu-bar' onSubmit={this.onFormSubmit}>
                <div>
                    <label>cube number </label>
                    <input type='number' name='cubeNumber' value={cubeNumber} onChange={this.onNumberChange} />
                </div>

            </form>

            <CubeRender
                cubeArray={cubeArray}
                cubeSize={cubeSize}
            />
        </div>
    )
}

}

您正在通过写入 array[randIndex] = this.randomColor() 直接改变您的状态。仅此一项(不推荐)不会重新渲染您的组件。当您随后编写 this.setState({}); 时,组件将以您刚刚更改的状态重新呈现。

您可以改为创建 cubeArray 数组的副本,并用随机颜色覆盖随机索引,然后用它更新您的状态。

randomBlinking = () => {
  this.blinking = setInterval(() => {
    this.setState(previousState => {
      const cubeArray = [...previousState.cubeArray];
      const randIndex = Math.floor(Math.random() * cubeArray.length);

      cubeArray[randIndex] = this.randomColor();

      return { cubeArray };
    });
  }, 500);
};