输入寄存器时,我选择显示全年的数据,然后转到图表,所有内容都会显示,当我在寄存器中没有选择任何内容并立即切换到图表时,收到没有图表的错误,如何立即显示它们,而不是魔术?
charts.js
@connect(
state => ({
articles: state.articles.items,
registers: state.registers.items,
filter_years: state.registers.years,
nextWorkspace: state.workspaces.app.next,
isResolved: {
registers: state.subscriptions.registers.resolved
}
}),
dispatch => ({
actions: bindActionCreators({
...subscriptionActions,
...workspaceActions,
toaster,
fetchRegisters
}, dispatch)
})
)
export default class Charts extends Component {
constructor(props) {
super(props);
this.types = ['Revenue', 'Cost'],
this.toaster = props.actions.toaster();
this.subscriptions = ['articles'],
this.state = this.createInitialState()
}
componentWillMount() {
this.props.actions.subscribe(this.subscriptions)
.then(() => {
this.props.actions.fetchRegisters({year: this.state.currentYear, month: defaultMonths()})
.then(() => {
if (!this.props.registers.length) {
this.toaster.warning('There is no data for charts')
}
this.createReportState()
})
})
}
componentWillReceiveProps() {
if (this.isNextWorkspaceChanged()) {
this.props.actions.fetchRegisters({ year: this.state.currentYear, month: defaultMonths() })
.then(() => this.createReportState())
}
}
componentWillUnmount() {
this.props.actions.unsubscribe(this.subscriptions)
}
isNextWorkspaceChanged() {
return this.props.actions.isNextWorkspaceChanged(this.props.nextWorkspace.id)
}
createInitialState() {
let currentYear = new Date().getFullYear()
let initData = new Array(12)
initData.fill(0)
return {
currentYear: currentYear,
chartsData: {
Revenue: Object.assign([], initData),
Cost: Object.assign([], initData),
Profit: Object.assign([], initData)
}
}
}
createReportState() {
const {registers, articles} = this.props
const {currentYear} = this.state
this.state = this.createInitialState()
let chartsData = Object.assign([], this.state.chartsData);
registers.forEach(register => {
let dataNow = new Date(register.date)
let modelMoun = monthsNames[dataNow.getMonth()]
let numModelMoun = dataNow.getMonth()
const article = articles.find(article => article.id === register.article_id)
let modelTypeArticle = article.type
chartsData[modelTypeArticle][numModelMoun] += Math.round(register.value)
chartsData['Profit'][numModelMoun] = Math.round(chartsData['Revenue'][numModelMoun] - chartsData['Cost'][numModelMoun])
})
this.setState({
currentYear,
chartsData: chartsData
});
}
handleYearChange = e => {
if (this.state.isError) return
const year = e.value
setStatePromise(this, (prevState => ({
currentYear: year
}))).then(() => {
this.props.actions.fetchRegisters({year: year, month: defaultMonths()})
.then(() => {
if (!this.props.registers.length) {
this.toaster.warning('There is no data for charts')
}
this.createReportState()
})
})
}