react echarts刷新不顯示問題的解決方法
更新時間:2024年02月29日 10:40:18 作者:huoyueyi
最近在寫項目的時候遇到了一個問題,當(dāng)編輯完代碼后echarts圖正常展示 , 可再次刷新頁面 , echarts會消失,所以本文給大家介紹了react echarts刷新不顯示問題原因和解決方法,需要的朋友可以參考下
遇到了一個問題 , 當(dāng)編輯完代碼后echarts圖正常展示 , 可再次刷新頁面 , echarts會消失
問題如下圖
要實現(xiàn)的效果
原因 : ECharts 初始化時找不到對應(yīng)的 DOM 元素 , 在 React 中,DOM 元素是在組件渲染后才生成的,而你在初始化 ECharts 時試圖訪問還未渲染完成的 DOM 元素。
import React, { useEffect, useState, useRef } from 'react'; import aa from '@/assets/images/圖標(biāo).png'; import bb from '@/assets/images/圖標(biāo)1.png'; import cc from '@/assets/images/圖標(biāo)2.png'; import dd from '@/assets/images/圖標(biāo)3.png'; import * as echarts from 'echarts'; import { salesStatistics } from './request'; const OrderSalesStatistics = () => { const sale = (data) => { const xAxisData = data.map((item) => item.month); const seriesData = data.map((item) => item.price); const saleOption = { title: { text: '銷售總金額(元)/月', left: 'left', }, tooltip: { trigger: 'axis', axisPointer: { type: 'shadow', }, }, grid: { left: '3%', right: '4%', bottom: '3%', containLabel: true, }, xAxis: [ { type: 'category', data: xAxisData, axisTick: { alignWithLabel: true, }, axisLabel: { interval: 0, // 強(qiáng)制顯示所有標(biāo)簽 formatter: function (value, index) { // 僅顯示 1、3、5、7、9、11 月的標(biāo)簽 if ((index + 1) % 2 !== 0) { return value + '月'; } else { return ''; } }, }, }, ], yAxis: [ { type: 'value', splitLine: { show: false, // 取消 y 軸的橫線 }, }, ], series: [ { name: 'Direct', type: 'bar', barWidth: '60%', data: seriesData, itemStyle: { color: '#d48ca0', }, }, ], }; const saleEchart = echarts.init(document.getElementById('totalSalesAmount')); saleEchart.setOption(saleOption); }; const teachers = (data) => { const seriesData = data.map((item) => ({ name: item.teacher_name, value: item.price, })); const option = { title: { text: '老師業(yè)績分布TOP10', left: 'left', }, tooltip: { trigger: 'item', }, legend: { orient: 'horizontal', // 將 orient 設(shè)置為 'horizontal' top: '5%', // 調(diào)整 top 屬性的值,控制圖例位置 }, series: [ { name: 'Access From', type: 'pie', radius: '50%', data: seriesData, emphasis: { itemStyle: { shadowBlur: 10, shadowOffsetX: 0, shadowColor: 'rgba(0, 0, 0, 0.5)', }, }, labelLine: { show: false, }, label: { // 添加label屬性,在formatter函數(shù)中獲取price和ratio formatter: function (params) { const { price, ratio } = data[params.dataIndex]; return `${params.name} ${(ratio * 100).toFixed(2)}%`; }, }, }, ], }; const teacherEchart = echarts.init(document.getElementById('teacherPerformance')); teacherEchart.setOption(option); }; const books = (data) => { const seriesData = data.map((item) => ({ name: item.book_name, value: item.price, })); console.log('seriesData-book', seriesData); const option = { title: { text: '書籍業(yè)績分布TOP10', left: 'left', }, tooltip: { trigger: 'item', formatter: function (params) { return `<div style="display: flex; align-items: center;"> <div style="width: 10px; height: 10px; border-radius: 50%; background-color: ${params.color}; margin-right: 10px;"></div> <span style="color: ${params.color}">鏡像地址</span> : ${params.name} </div>`; }, }, series: [ { name: '庫存情況', type: 'pie', radius: '68%', center: ['50%', '50%'], clockwise: false, data: seriesData, label: { normal: { textStyle: { color: '#999', fontSize: 14, }, }, }, labelLine: { //取消選中餅圖后往外指的小橫線 normal: { show: false, }, }, itemStyle: { //餅圖之間的間距 normal: { borderWidth: 4, borderColor: '#ffffff', }, emphasis: { borderWidth: 0, shadowBlur: 10, shadowOffsetX: 0, shadowColor: 'rgba(0, 0, 0, 0.5)', }, }, }, ], color: ['#00acee', '#52cdd5', '#79d9f1', '#a7e7ff', '#c8efff'], backgroundColor: '#fff', }; const bookEchart = echarts.init(document.getElementById('bookPerformance')); bookEchart.setOption(option); }; const [tabArr, setTabArr] = useState([]); const [type, setType] = useState(''); // 在組件內(nèi)部定義 refs , 解決一刷新就消失 const totalSalesAmountRef = useRef(null); const teacherPerformanceRef = useRef(null); const bookPerformanceRef = useRef(null); const initAllEcharts = async () => { const data = await salesStatistics(); let { salesAmount, teacher, book, order_num, buy_num, average, income } = data; setType(data.type); console.log('type', type); if (data.type === 2) { sale(salesAmount); books(book); } else if (data.type === 1) { sale(salesAmount); teachers(teacher); } setTabArr([ { name: '總訂單數(shù)', value: order_num }, { name: '總購買人數(shù)', value: buy_num }, { name: '平均客單價', value: average }, { name: '預(yù)計總收入', value: income }, ]); }; useEffect(() => { initAllEcharts(); }, []); useEffect(() => { const initCharts = async () => { const data = await salesStatistics(); let { salesAmount, teacher, book, order_num, buy_num, average, income } = data; setType(data.type); if (data.type === 2) { if (totalSalesAmountRef.current && bookPerformanceRef.current) { sale(salesAmount, totalSalesAmountRef.current); books(book, bookPerformanceRef.current); } } else if (data.type === 1) { if (totalSalesAmountRef.current && teacherPerformanceRef.current) { sale(salesAmount, totalSalesAmountRef.current); teachers(teacher, teacherPerformanceRef.current); } } setTabArr([ { name: '總訂單數(shù)', value: order_num }, { name: '總購買人數(shù)', value: buy_num }, { name: '平均客單價', value: average }, { name: '預(yù)計總收入', value: income }, ]); }; initCharts(); }, []); return ( <div className='sales'> <div className='items'> {tabArr.map((item, index) => ( <div className='item' key={Math.random()}> <div className='img'> {index === 0 && <img src={aa} alt='' />} {index === 1 && <img src={bb} alt='' />} {index === 2 && <img src={cc} alt='' />} {index === 3 && <img src={dd} alt='' />} </div> <div className='cont'> <div className='title'>{item.name}</div> <div className='total'>{item.value}</div> </div> </div> ))} </div> <div className='echarts'> // html部分也要加上ref {type === 1 ? ( <> <div className='echarts-item' id='totalSalesAmount' ref={totalSalesAmountRef}></div> <div className='echarts-item' id='teacherPerformance' ref={teacherPerformanceRef}></div> </> ) : type === 2 ? ( <> <div className='echarts-item' id='totalSalesAmount' ref={totalSalesAmountRef}></div> <div className='echarts-item' id='bookPerformance' ref={bookPerformanceRef}></div> </> ) : null} </div> </div> ); }; export default OrderSalesStatistics;
到此這篇關(guān)于react echarts刷新不顯示問題的解決方法的文章就介紹到這了,更多相關(guān)react echarts刷新不顯示內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
ahooks useVirtualList 封裝虛擬滾動列表
這篇文章主要為大家介紹了ahooks useVirtualList 封裝虛擬滾動列表詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-09-09