React - ShowRainBow.state:必须设置为对象或为空

IT技术 reactjs
2021-05-03 06:04:43

我有两个组件。

  1. 彩虹.jsx
  2. 彩虹列表.jsx

RainBow.jsx 是具有数组和 RainBowList.jsx 的主要组件,我使用 map() 以 li 格式显示所有彩虹色。

我在控制台日志中收到错误ShowRainBow.state: must set to an object or null

我的代码

彩虹.jsx

// Let's import React
import React from "react";

// Import custom component
import RainBowList from "./RainBowList.jsx";

// Let's create component [[ShowRainBow]]
class ShowRainBow extends React.Component{

    // constructor class
    constructor(){
        super();

        // use state with array
        let rainbowColor = this.state = ["red", "orange", "yellow", "green", "blue", "indigo", "violet"];

    }   

    render(){       

        return(
            <div className="row">

                <div className="col-12 col-sm-12 col-md-12 col-lg-12 col-xl-12">   
                    <RainBowList checkColor={this.state.rainbowColor} />
                </div>

            </div>
        );
    }
}

// Let's render ReactDOM
export default ShowRainBow;

彩虹列表.jsx

// Let's import react
import React from "react";

// Let's create component [[RainBowList]]
class RainBowList extends React.Component{
    render(){
        return(
            <ul>
                <li> Show rainbow colors </li>
                {
                    this.props.checkColor.map( rainbowcolors =>{
                        return <li rainbowcolors={rainbowcolors} key={rainbowcolors}> {rainbowcolors} </li>
                    })
                }

            </ul>
        );
    }
}

// Let's render ReactDOM
export default RainBowList;
1个回答

您必须将stateofShowRainBow组件设置为对象而不是数组,如下所示

constructor(){
       super();
       this.state = {rainbowColor: ["red", "orange", "yellow", "green", "blue", "indigo", "violet"]};
}