[英]How do I create an array of objects in a React class component through a for loop to be mapped in a functional component?
I created the following class component with React:我使用 React 创建了以下 class 组件:
I want the daysArrayState object to hold an array of objects that is create through the addDay arrow function.我希望 daysArrayState object 保存通过 addDay 箭头 function 创建的对象数组。
state = {
daysArray: []
}
days = () => {
let daysArrayCopy = [];
for(let i=1; i >= 35; i++){
let id = Math.random();
let num = i;
let day = {
dayId: id,
dayNum: num
}
daysArrayCopy = [...this.state.daysArrayState, day];
this.setState({daysArray: daysArrayCopy});
}
}
render(){
this.days();
return(
<div className="grid calendar-template">
<div className="grid">Left</div>
<div>
<div className="grid text-center month-title">
January
</div>
<div>
<DayBox days = {this.state.daysArray}></DayBox>
</div>
</div>
<div className="grid">Right</div>
</div>
)
}
I have another functional component that is meant to map through the daysArrayState object:我有另一个功能组件,用于 map 通过 daysArrayState object:
const DayBox = ({days}) => {
const daysList = days.map(day => {
return(
<div className="grid dayBox-template text-center" key={day.dayId}>
{day.dayNum}
</div>
)
})
return(
<div className="grid week-grid">
{daysList}
</div>
)
When I try to do this I get an error as the parameter I appear to be passing is the addDay function and not the array of objects in daysArrayState.当我尝试执行此操作时出现错误,因为我传递的参数似乎是 addDay function 而不是 daysArrayState 中的对象数组。
Here is your main component:这是您的主要组件:
class App extends Component {
state = {
days: []
};
//call the function in this lifecycle method
componentDidMount() {
this.addDay();
}
//see the updated logic for your addDay
addDay = () => {
const daysArrayCopy = [];
for (let i = 0; i <= 35; i++) {
let id = Math.random();
let num = i;
let day = {
dayId: id,
dayNum: num
};
daysArrayCopy.push(day);
}
this.setState({ days: [...this.state.days, ...daysArrayCopy] });
};
render() {
return (
<div className="grid calendar-template">
<div className="grid">Left</div>
<div>
<div className="grid text-center month-title">January</div>
<div>
<DayBox days={this.state.days} /> //pass the state here
</div>
</div>
<div className="grid">Right</div>
</div>
);
}
}
Here is your DayBox
component:这是您的
DayBox
组件:
export default function DayBox({ days }) {
return (
<div className="grid week-grid">
{days.map(day => (
<div key={day.dayId}>{day.dayNum}</div>
))}
</div>
);
}
Here is a live demo: https://stackblitz.com/edit/react-zvzfwu?file=index.js这是一个现场演示: https://stackblitz.com/edit/react-zvzfwu?file=index.js
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.