我有两个组成部分。
RainBow.jsx是主要组件,有阵列和RainBowList.jsx我用它来显示li格式的所有彩虹颜色和map()。
我在控制台日志中收到错误 ShowRainBow.state:必须设置为对象或null
我的代码
RainBow.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;
RainBowList.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;
答案 0 :(得分:2)
您必须将state
组件的ShowRainBow
设置为对象而不是数组,如此
constructor(){
super();
this.state = {rainbowColor: ["red", "orange", "yellow", "green", "blue", "indigo", "violet"]};
}