项目场景:
用日历显示日志状态
问题描述:
想重新选择年月查看日志状态,查到数据了,但是?dateCellRender 方法已经执行完毕了,导致刷新不及时,点击一下日历面板 才能显示
原因分析:
官方给的文档每个日期渲染的单元格数据是无状态的,可以把dateCellRender函数设置成一个有状态的组件,当数据变化时,在重新render
下面是一个简单的示例代码
import React, { PureComponent } from 'react';
import { withRouter } from 'react-router-dom'
import { connect } from 'react-redux'
import { Button, Row, Col, Card, Form, Divider, Table, Tree, message, Modal, Upload, Calendar, Badge } from 'antd';
import { Input, DatePicker, Select, Switch, Radio, Checkbox, Cascader, InputNumber } from 'antd';
class DataCellRender extends PureComponent {
constructor(props) {
super(props)
this.state = {
component: <div></div>
}
this.reload = this.reload.bind(this)
}
componentDidMount() {
this.reload()
}
componentWillReceiveProps(nextProps) {
if (nextProps.dataSource !== this.props.dataSource) {
this.reload(nextProps.dataSource)
}
}
reload(dataSource = this.props.dataSource) {
let component = <div></div>
let currentDate = moment(this.props.value).format('YYYY-MM-DD')
// currentDate 是每一个日期单元格触发dateCellRender 返回的参数(当前单元格日期) 具体业务可以结合当前选择的日期value和自定义数据datacouce 来组合
component = <ul className="events">
<li>
<Badge color="#ff0000" text={dataSource} />
</li>
</ul>
this.setState({
component,
})
}
render() {
return this.state.component
}
}
@withRouter
@connect(
state => ({
})
)
class Panel extends React.PureComponent {
constructor(props) {
super(props);
this.state = {
dataSource: moment().format("yyyy-MM-DD"),
}
this.onPanelChange = this.onPanelChange.bind(this)
}
componentDidMount() {
}
onPanelChange(e) { //选择日期的回调函数
let date = e['_d'] //日期的moment对象
this.setState({
dataSource: moment(date).format("yyyy-MM-DD")
})
}
render() {
return (
<Card style={{ padding: 10 }}>
<Calendar dateCellRender={value => <DataCellRender value={value} dataSource={this.state.dataSource} />} onPanelChange={this.onPanelChange} />
</Card>
)
}
}
export default Panel
|