警告:setState(...):只能更新已安装或安装的组件。这通常意味着

时间:2018-03-12 21:28:50

标签: javascript reactjs

我正在Udemy Advanced Webdeveloper Bootcamp中进行练习。练习要求提出一个32页的随机改变颜色的页面(每x秒)。我的解决方案并非如此。我同时改变了所有32个盒子的颜色。它几乎可以工作。我最初得到随机的32个盒子,但之后不会改变颜色。我的控制台告诉我我在使用setState做错了。但我无法弄清楚是什么。我认为我的changeColor是一个纯函数:

import React, { Component } from 'react';
import './App.css';

class Box extends Component {
    render() {

        var divStyle = {
            backgroundColor: this.props.color
        }

        return(
            <div className="box" style={divStyle}></div>
        );
    }
}

class BoxRow extends Component {
    render() {
        const numOfBoxesInRow = 8;
        const boxes = [];

        for(var i=0; i < numOfBoxesInRow; i++) {
            boxes.push(<Box color={this.props.colors[i]} key={i+1}/>);
        }

        return(
            <div className="boxesWrapper">
            {boxes}
            </div>
            );
    }
}

class BoxTable extends Component {

    constructor(props) {
        super(props);
        this.getRandom = this.getRandom.bind(this);
        this.changeColors = this.changeColors.bind(this);
        this.state = {
            randomColors: this.getRandom(this.props.allColors, 32) // hardcoding
        };

        this.changeColors();
    }

    changeColors() {
        setInterval(
            this.setState({randomColors: this.getRandom(this.props.allColors, 32)}), 5000);
    }

    getRandom(arr, n) {
        var result = new Array(n),
            len = arr.length,
            taken = new Array(len);
        if (n > len)
            throw new RangeError("getRandom: more elements taken than available");
        while (n--) {
            var x = Math.floor(Math.random() * len);
            result[n] = arr[x in taken ? taken[x] : x];
            taken[x] = --len in taken ? taken[len] : len;
        }
        return result;
    }

    render () {
        const numOfRows = 4;
        const rows = [];

        for(let i=0; i < numOfRows; i++) {
          rows.push(
              <BoxRow colors={this.state.randomColors.slice(8*i,8*(1+i))} key={i+1}/>
            )
        }

        return (
          <div className="rowsWrapper">
          {rows}
          </div>
        );
    }
}

BoxTable.defaultProps = {
    allColors: ["AliceBlue","AntiqueWhite","Aqua","Aquamarine","Azure","Beige",
    "Bisque","Black","BlanchedAlmond","Blue","BlueViolet","Brown","BurlyWood",
    "CadetBlue","Chartreuse","Chocolate","Coral","CornflowerBlue","Cornsilk",
    "Crimson","Cyan","DarkBlue","DarkCyan","DarkGoldenRod","DarkGray","DarkGrey",
    "DarkGreen","DarkKhaki","DarkMagenta","DarkOliveGreen","Darkorange",
    "DarkOrchid","DarkRed","DarkSalmon","DarkSeaGreen","DarkSlateBlue",
    "DarkSlateGray","DarkSlateGrey","DarkTurquoise","DarkViolet","DeepPink",
    "DeepSkyBlue","DimGray","DimGrey","DodgerBlue","FireBrick","FloralWhite",
    "ForestGreen","Fuchsia","Gainsboro","GhostWhite","Gold","GoldenRod","Gray",
    "Grey","Green","GreenYellow","HoneyDew","HotPink","IndianRed","Indigo",
    "Ivory","Khaki","Lavender","LavenderBlush","LawnGreen","LemonChiffon",
    "LightBlue","LightCoral","LightCyan","LightGoldenRodYellow","LightGray",
    "LightGrey","LightGreen","LightPink","LightSalmon","LightSeaGreen",
    "LightSkyBlue","LightSlateGray","LightSlateGrey","LightSteelBlue",
    "LightYellow","Lime","LimeGreen","Linen","Magenta","Maroon",
    "MediumAquaMarine","MediumBlue","MediumOrchid","MediumPurple",
    "MediumSeaGreen","MediumSlateBlue","MediumSpringGreen","MediumTurquoise",
    "MediumVioletRed","MidnightBlue","MintCream","MistyRose","Moccasin",
    "NavajoWhite","Navy","OldLace","Olive","OliveDrab","Orange","OrangeRed",
    "Orchid","PaleGoldenRod","PaleGreen","PaleTurquoise","PaleVioletRed",
    "PapayaWhip","PeachPuff","Peru","Pink","Plum","PowderBlue","Purple",
    "Red","RosyBrown","RoyalBlue","SaddleBrown","Salmon","SandyBrown",
    "SeaGreen","SeaShell","Sienna","Silver","SkyBlue","SlateBlue","SlateGray",
    "SlateGrey","Snow","SpringGreen","SteelBlue","Tan","Teal","Thistle",
    "Tomato","Turquoise","Violet","Wheat","White","WhiteSmoke","Yellow","YellowGreen"]
}

export default BoxTable

4 个答案:

答案 0 :(得分:1)

您需要使用lambda函数才能在setInterval

中使用setState
setInterval(() => {
        this.setState({randomColors: this.getRandom(this.props.allColors, 
                       32)});
                  }, 5000)

答案 1 :(得分:1)

尝试将changeColors函数更改为:

changeColors() {
        setInterval(() => this.setState({randomColors: this.getRandom(this.props.allColors, 32)}), 5000);
    }

setInterval的第一个参数是函数,在原始代码中你已经执行了这个setState并且没有传递函数本身

答案 2 :(得分:1)

您需要在组件创建阶段componentDidMount()

之后更新状态
class BoxTable extends Component {

    constructor(props) {
        super(props);
        this.getRandom = this.getRandom.bind(this);
        this.changeColors = this.changeColors.bind(this);
        this.state = {
            randomColors: this.getRandom(this.props.allColors, 32) // hardcoding
        };

        // delete this line 
        //this.changeColors();
    }
    // replace changeColors by componentDidMount, 
    // this function will be called automatically by react
    componentDidMount() {
        setInterval(
            this.setState({randomColors: this.getRandom(this.props.allColors, 32)}), 5000);
    }

    getRandom(arr, n) {
        var result = new Array(n),
            len = arr.length,
            taken = new Array(len);
        if (n > len)
            throw new RangeError("getRandom: more elements taken than available");
        while (n--) {
            var x = Math.floor(Math.random() * len);
            result[n] = arr[x in taken ? taken[x] : x];
            taken[x] = --len in taken ? taken[len] : len;
        }
        return result;
    }

    render () {
        const numOfRows = 4;
        const rows = [];

        for(let i=0; i < numOfRows; i++) {
          rows.push(
              <BoxRow colors={this.state.randomColors.slice(8*i,8*(1+i))} key={i+1}/>
            )
        }

        return (
          <div className="rowsWrapper">
          {rows}
          </div>
        );
    }
}

答案 3 :(得分:1)

在组件挂载之前(从构造函数)调用this.setState。请尝试从this.ChangeColors生命周期功能中创建第一个componentDidMount

此外,清除componentWillUnMount

中卸载的时间间隔并不是一个坏主意。

编辑:通过在第一次等待后更改要调用的间隔,可以防止出现错误,现在。我建议使用生命周期功能来养成良好的习惯。这只是一个临时的任务,但是在一个完整的项目中,你可能会在以后通过在this.setState可靠地安装之前调用template <typename T> template <typename E> //... 来再次破坏组件的风险。