如何在多个状态更改的每个状态上重新呈现组件?

时间:2020-10-18 17:55:56

标签: javascript reactjs setstate

我仍在学习JS / React,所以这很可能是我做错了。欢迎任何批评。

我有一个带有图纸的画布。我想在按下按钮时多次更改绘图的颜色。 要明确:我想要单击按钮多次更改绘图的颜色。

我尝试了几种不同的方法,但是它们是两种的混浊变化:

  • 按下按钮时,它将调用将多次更改状态的方法,但React仅会打扰呈现我设置的最后一个状态。 (有道理)

  • 为每个setTimeout使用setState,但似乎破坏了方法,并且渲染永不改变。

这是示例代码:

import React from 'react';

class App extends React.Component {
 constructor(props) {
      super(props);
      this.state = {
        color: "#000000",
      }
      this.changeColors = this.changeColors.bind(this);
  }
  
  changeColors() {
    let colors = ["#000000", "#0000FF", "#FF0000", "#00FF00"];
    for (let nextColor in colors) {
      console.log(`Color now ${colors[nextColor]}`);
      // This seems to break it
      //setTimeout(function(){ this.setState({color: colors[nextColor]}); }, 3000);

      // This only renders last state
      this.setState({color: colors[nextColor]});
    }
  }

  render() {
    return (
      <div className="App">
        <h1>Change Colors</h1>
        <MyButton changeColor={this.changeColors}/>
        <MyCanvas color={this.state}/>
      </div>
    );
  }
}

class MyButton extends React.Component {
  render() {
    return (
      <button 
        type="button" 
        className="btn btn-secondary" 
        onClick={() => this.props.changeColor()}>
        Color
      </button>
    );
  }
}

class MyCanvas extends React.Component {
  componentDidMount() {
      this.drawOnCanvas(this.props.color)
  }
  
  componentDidUpdate() {
      this.drawOnCanvas(this.props.color)
  }
  
  drawOnCanvas(color) {
    const ctx = this.refs.canvas.getContext('2d');
    ctx.clearRect(0, 0, 300, 300) 
    ctx.fillStyle=color.color;
    ctx.fillRect(10, 10, 100, 100);
  }
  
  render() {
    return (
      <canvas id="canvas" ref="canvas" width={300} height={300}/>
    );
  }
}

export default App;

我做错了什么,如何通过反应实现多种颜色变化?

1 个答案:

答案 0 :(得分:2)

在没有setTimeout的情况下,所有渲染基本上都将合并为一个,这就是React的工作方式。但是,您可以尝试使用动态超时的setTimeout

class App extends React.Component {
 constructor(props) {
      super(props);
      this.state = {
        color: "#000000",
      }
  }
  
  changeColors = () => {
    let colors = ["#000000", "#0000FF", "#FF0000", "#00FF00"];
    colors.forEach((color, i) => {
      setTimeout(() => {
          this.setState({ color });
      }, 500 * i);
    });
  }

  render() {
    return (
      <div className="App" style={{ color: this.state.color }}>
        <h1>Change Colors</h1>
        <button onClick={this.changeColors}>change</button>
      </div>
    );
  }
}

ReactDOM.render(<App />, document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id='root'></div>