欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

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)文章

  • React精髓!一篇全概括小結(jié)(急速)

    React精髓!一篇全概括小結(jié)(急速)

    這篇文章主要介紹了React精髓!一篇全概括小結(jié)(急速),小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2019-05-05
  • ahooks useVirtualList 封裝虛擬滾動列表

    ahooks useVirtualList 封裝虛擬滾動列表

    這篇文章主要為大家介紹了ahooks useVirtualList 封裝虛擬滾動列表詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2022-09-09
  • React memo減少重復(fù)渲染詳解

    React memo減少重復(fù)渲染詳解

    React.memo為高階組件。它與React.PureComponent 非常相似,但它適用于函數(shù)組件,但不適用于class組件。文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2022-10-10
  • 一文理解Redux及其工作原理

    一文理解Redux及其工作原理

    這篇文章主要介紹了一文理解R通過圍繞主題展開詳細(xì)edux及其工作原理,文章通過主題展開詳細(xì)的內(nèi)容介紹,具有一定的參考價值,需要的小伙伴可以參考一下
    2022-09-09
  • 深入淺析react native es6語法

    深入淺析react native es6語法

    這篇文章主要介紹了深入淺析react native es6語法的相關(guān)資料,需要的朋友可以參考下
    2015-12-12
  • React中immutable的UI組件渲染性能詳解

    React中immutable的UI組件渲染性能詳解

    這篇文章主要為大家介紹了React中immutable的UI組件渲染性能詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2023-04-04
  • React State與生命周期詳細(xì)介紹

    React State與生命周期詳細(xì)介紹

    React將組件(component)看成一個狀態(tài)機(jī)(State Machines),通過其內(nèi)部自定義的狀態(tài)(State)和生命周期(Lifecycle)實現(xiàn)并與用戶交互,維持組件的不同狀態(tài)
    2022-08-08
  • React中的render何時執(zhí)行過程

    React中的render何時執(zhí)行過程

    這篇文章主要介紹了React中的render何時執(zhí)行過程,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2018-04-04
  • 基于React實現(xiàn)倒計時功能

    基于React實現(xiàn)倒計時功能

    這篇文章主要為大家詳細(xì)介紹了如何基于React實現(xiàn)倒計時功能,文中的示例代碼講解詳細(xì),具有一定的借鑒價值,有需要的小伙伴可以參考一下
    2024-02-02
  • ReactNative列表ListView的用法

    ReactNative列表ListView的用法

    本篇文章主要介紹了ReactNative列表ListView的用法,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2017-08-08

最新評論