首页 > 建站教程 > APP开发,混合APP >  react-native的native-echarts更新数据会刷新闪烁的bug修复正文

react-native的native-echarts更新数据会刷新闪烁的bug修复

react-native的native-echarts在更新数据的时候,老是会闪烁,应该是过度渲染的问题导致的。其实echarts本身的渲染机制是非常优秀的。闪烁是此插件本身的问题。下面是修复方法,亲测可用:

一、找到node_modules/native-echarts/src/components/Echarts/index.js,替换为下面的内容
import React, { Component } from 'react';
import { View, StyleSheet, Platform } from 'react-native';
import { WebView } from 'react-native-webview'
import renderChart from './renderChart';
import renderChartNoFirst from './renderChart'
import echarts from './echarts.min';

export default class App extends Component {
  // 新增代码
  shouldComponentUpdate(nextProps, nextState) {
    const thisProps = this.props || {}
    nextProps = nextProps || {}
    if (Object.keys(thisProps).length !== Object.keys(nextProps).length) {
      return true
    }
    for (const key in nextProps) {
      if (JSON.stringify(thisProps[key]) != JSON.stringify(nextProps[key])) {
        // console.log('props', key, thisProps[key], nextProps[key])
        return true
      }
    }
    return false
  }

  // 新增代码
  componentWillReceiveProps(nextProps) {
    if(nextProps.option !== this.props.option) {
      this.refs.chart.injectJavaScript(renderChart(nextProps,false))
    }
  }

  render() {
    if (Platform.OS == 'android'){
      return (
        <View style={{flex: 1, height: this.props.height || 400,}}>
          <WebView
            ref="chart"
            scrollEnabled = {false}
            injectedJavaScript = {renderChart(this.props,true)}
            style={{
              height: this.props.height || 400,
            }}
            //source={require('./tpl.html')}
            source={{uri: 'file:///android_asset/tpl.html'}}
          />
        </View>
      );
    }else{
      return (
        <View style={{flex: 1, height: this.props.height || 400,}}>
          <WebView
            ref="chart"
            scrollEnabled = {false}
            scalesPageToFit={false}
            injectedJavaScript = {renderChart(this.props,true)}
            style={{
              height: this.props.height || 400,
            }}
            source={require('./tpl.html')}
          />
        </View>
      );
    }
  }
}
注意,WebView的引用,和原插件不一样,原插件是上一行引入的,这里改为从react-native-webview引入,详见:react-native native-echarts使用方法指南

二、找到node_modules/native-echarts/src/components/Echarts/renderChart.js
import echarts from './echarts.min';
import toString from '../../util/toString';
var myChart = null;
export default function renderChart(props,isFirst) {
  const height = props.height || 400;
    if (isFirst){
      return `
    document.getElementById('main').style.height = "${height}px";
    myChart = echarts.init(document.getElementById('main'));
    myChart.setOption(${toString(props.option)});
  `
    }else{
      return `
    document.getElementById('main').style.height = "${height}px";
    
    myChart.setOption(${toString(props.option)});
  `
    }
}