我只是试图创建一个非常简单的应用程序,我将输入一个数字,计算机将生成具有该数字的框,并一次随机更改一个框的颜色。该代码有效,但我不明白它为什么起作用,在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>
)
}
}
答案 0 :(得分:2)
您正在通过写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);
};