最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

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, // 強制顯示所有標(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)文章

  • React路由跳轉(zhuǎn)的實現(xiàn)示例

    React路由跳轉(zhuǎn)的實現(xiàn)示例

    在React中,可以使用多種方法進行路由跳轉(zhuǎn),本文主要介紹了React路由跳轉(zhuǎn)的實現(xiàn)示例,具有一定的參考價值,感興趣的可以了解一下
    2023-12-12
  • React-Hooks之useImperativeHandler使用介紹

    React-Hooks之useImperativeHandler使用介紹

    這篇文章主要為大家介紹了React-Hooks之useImperativeHandler使用介紹,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪
    2023-07-07
  • React forwardRef的使用方法及注意點

    React forwardRef的使用方法及注意點

    React.forwardRef的API中ref必須指向dom元素而不是React組件,通過一段示例代碼給大家介紹了React forwardRef使用方法及注意點還有一些特殊情況分析,感興趣的朋友跟隨小編一起看看吧
    2021-06-06
  • react native環(huán)境安裝流程

    react native環(huán)境安裝流程

    React Native 是目前流行的跨平臺移動應(yīng)用開發(fā)框架之一。本文介紹react native環(huán)境安裝流程及遇到問題解決方法,感興趣的朋友一起看看吧
    2021-05-05
  • react native創(chuàng)建項目常用插件詳解

    react native創(chuàng)建項目常用插件詳解

    文章詳細介紹了React Native項目的頁面路徑目錄設(shè)計原則、路由管理、狀態(tài)管理、服務(wù)層管理、自定義hook和工具函數(shù)的使用方法、適配方案以及樣式排列對齊方式,通過這些原則和方法,可以提高項目的可維護性和可擴展性
    2025-12-12
  • React前端路由應(yīng)用介紹

    React前端路由應(yīng)用介紹

    前端應(yīng)用大多數(shù)是SPA(單頁應(yīng)用程序),也就是只有一個HTML頁面的應(yīng)用程序。因為它的用戶體驗更好、對服務(wù)器壓力更小,所以更受歡迎。為了有效的使用單個頁面來管理多頁面的功能,前端路由應(yīng)運而生
    2022-09-09
  • react性能優(yōu)化useMemo與useCallback使用對比詳解

    react性能優(yōu)化useMemo與useCallback使用對比詳解

    這篇文章主要為大家介紹了react性能優(yōu)化useMemo與useCallback使用對比詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪
    2022-08-08
  • Redux Toolkit 實戰(zhàn)小結(jié)

    Redux Toolkit 實戰(zhàn)小結(jié)

    Redux曾是React狀態(tài)管理的標(biāo)準(zhǔn)解決方案,但傳統(tǒng) Redux 的樣板代碼過多、配置復(fù)雜、異步處理繁瑣,Redux Toolkit(RTK)官方推出,旨在解決這些痛點,下面就來詳細的介紹一下如何使用
    2026-03-03
  • React.memo函數(shù)中的參數(shù)示例詳解

    React.memo函數(shù)中的參數(shù)示例詳解

    這篇文章主要為大家介紹了React.memo函數(shù)中的參數(shù)示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪
    2022-09-09
  • React項目中使用Redux的?react-redux

    React項目中使用Redux的?react-redux

    這篇文章主要介紹了React項目中使用Redux的?react-redux,文章圍繞主題展開詳細的內(nèi)容介紹,具有一定的參考價值,需要的小伙伴可以參考一下
    2022-09-09

最新評論

新民市| 德惠市| 台州市| 正镶白旗| 紫云| 嵊州市| 阿拉善盟| 长兴县| 会昌县| 沙坪坝区| 贺州市| 铜川市| 旬邑县| 当雄县| 宣城市| 利川市| 大庆市| 汉源县| 长治县| 罗源县| 西林县| 沽源县| 眉山市| 清河县| 呼伦贝尔市| 荆州市| 固安县| 闽清县| 临澧县| 蓬溪县| 旬邑县| 汉阴县| 北宁市| 曲阳县| 吴江市| 罗源县| 林州市| 旌德县| 肥东县| 旅游| 永州市|