获取records数据,并使用dayjs库格式化日期
function Statistics() {
const [category, setCategory] = useState<'-'|'+'>('-')
const {records} = useRecords()
const {getTag} = useTags()
return (
<Layout>
<CategoryWrapper>
<CategorySection value={category}
onChange={value => setCategory(value)}/>
</CategoryWrapper>
{records.map(record => <div key={record.createAt}>
{record.tagIds.map(tagId => <span>{getTag(tagId)}</span>)}
<hr />
{record.amount}
<hr />
{day(record.createAt).format('YYYY年MM月DD日')}
</div>)}
</Layout>
);
}
将日期转化为今天昨天
const dayTransform = (date: string) => {
const now = day()
if(day(date).isSame(now, 'day')){
return '今天'
} else if(day(date).isSame(now.subtract(1, 'day'), 'day')){
return '昨天'
}
return date
}
对数据进行归类和排序
function Statistics() {
const [category, setCategory] = useState<'-'|'+'>('-')
const {records} = useRecords()
const {getTag} = useTags()
// 按日期归类
const hash:{[date: string]: RecordItem[]} = {}
records.filter(r => r.category === category).map(r => {
const date = day(r.createAt).format('YYYY-MM-DD')
if(!(date in hash)){
hash[date] = []
}
hash[date].push(r)
})
// 排序
const hashArray = Object.entries(hash).sort((a,b) => {
if(a[0] === b[0]) return 0;
if(a[0] > b[0]) return -1;
if(a[0] < b[0]) return 1;
return 0;
})
return (
<Layout>
<CategoryWrapper>
<CategorySection value={category}
onChange={value => setCategory(value)}/>
</CategoryWrapper>
{
hashArray.map(([date, records]) => (
<div key={date}>
<Header>{dayTransform(date)}</Header>
{records.map(record =>
<Item key={record.createAt}>
<div className="tags">
{record.tagIds.map(tagId => <span key={tagId}>{getTag(tagId)}</span>)
.reduce((result,span,index,array)=>
result.concat(index < array.length - 1 ? [span, ','] : [span]), [] as ReactNode[])}
</div>
<div className="note">
{record.note}
</div>
<div className="amount">
¥{record.amount}
</div>
</Item>)}
</div>
))
}
</Layout>
);
}
金额汇总
使用number-precision库处理浮点数精度问题
<Header>
<span>{dayTransform(date)}</span>
<span>¥{NP.strip(records.reduce((total, record) => total + record.amount, 0))}</span>
</Header>
React调试工具
让页面自动滚动到底部
通过scrollTop属性设置滚动
interface Props {
children: React.ReactNode,
className?: string,
scrollTop?: number
}
const Layout = (props: Props) => {
const mainRef = useRef<HTMLDivElement>(null)
useEffect(()=>{
setTimeout(()=>{
if(!mainRef.current) return;
mainRef.current.scrollTop = props.scrollTop!;
},0)
}, [props.scrollTop])
return (
<Wrapper>
<Main className={props.className} ref={mainRef}>
{props.children}
</Main>
<Nav />
</Wrapper>
)
}
Layout.defaultProps = {
scrollTop: 0
}