import React, { useEffect, useState } from "react";
const Dates = ({ dates }) => {
const [datesDivision, setDatesDivison] = useState({
0: [{ date: 20200501, isVailable: true }],
});
useEffect(() => {
setDatesDivison(divideDates());
}, [dates]);
const divideDates = () => { //function to seperate dates
let result = {
0: [{ date: 20200501, isVailable: true }]
};
let num = Math.ceil(dates.length / 8);
let count = 0;
for (let i = 0; i < num; i++) {
let item = [];
for (let j = count; j < count + 8; j++) {
if (dates[j] !== undefined) item.push(dates[j]);
}
count = count + 8;
result[i] = item;
}
return result;
};
return (
<div>
<div className="col2">
{datesDivision[0].map((item) => (
<div>{item.date.toString().substring(6, 8)}</div>
))}
</div>
</div>
);
};
// dates props
// [
// {date: 20200501, isVailable: true},
// {date: 20200502, isVailable: true},
// {date: 20200503, isVailable: true},
// {date: 20200504, isVailable: true},
// {date: 20200505, isVailable: true},
// {date: 20200506, isVailable: true},
// {date: 20200507, isVailable: true},
// {date: 20200508, isVailable: true},
// {date: 20200509, isVailable: true},
// {date: 20200510, isVailable: true},
// {date: 20200511, isVailable: true},
// {date: 20200512, isVailable: true},
//]
底部注释是日期道具。
要进行分页,我使用divideDates函数将日期道具按8个单位分为几组。
然后就是这样。
{
0:[{date: 20200501, isVailable: true},
{date: 20200502, isVailable: true},
{date: 20200503, isVailable: true},
{date: 20200504, isVailable: true},
{date: 20200505, isVailable: true},
{date: 20200506, isVailable: true},
{date: 20200507, isVailable: true},
{date: 20200508, isVailable: true},],
1:[{date: 20200509, isVailable: true},
{date: 20200510, isVailable: true},
{date: 20200511, isVailable: true},
{date: 20200512, isVailable: true},]
}
所以我在useEffect中使用setDatesDivison分配拆分结果。
当我将{}
分配给变量result
(divideDates函数的第一行)
我遇到了一个错误(无法读取未定义的属性“地图”)。
因此,地图功能无法正常工作。
但是当我将{ 0: [{ date: 20200501, isVailable: true }] }
分配给
变量result
(divideDates函数的第一行)
渲染成功。
我认为当第一次渲染setDatesDivison时,是从first declaration result
获得“结果”,而不是从return result
获得
我不了解生命周期的工作原理。