簡體   English   中英

React組件不會使用Redux Pros重新渲染ChartJS圖表

[英]React component wont re-render ChartJS chart with redux props

我在觸發React重新渲染用ChartJS繪制的圖表時遇到問題,我不知道是否需要每次都銷毀當前圖表並創建一個新圖表,但是我發誓它以前一直在工作,但現在不是,我不知道為什么TT

這是我的組件代碼:

import React, { PropTypes } from 'react';
import { connect } from 'react-redux';
import Chart from 'chart.js';


class ChartComp extends React.Component {
  constructor() {
    super()
    this.state = {
      data:[]
    }

    this.drawChart = this.drawChart.bind(this)
  }


  drawChart(){

    var myLineChart = new Chart(document.getElementById("line-chart"), {
          type: 'bar',
          data: {
            labels: this.props.chartData,
            datasets: [{
                data: this.props.chartData,
                label: "Active Users",
                backgroundColor: 'white'
              }
            ]
          },
          options: {
            responsive: true,
            mode: null,
            legend: { display: false },
            title: {
              display: true,
              text: 'User Activity',
              color: 'white'
            }
          }
        });
  }

  componentDidUpdate() {
    this.drawChart();
  }


  componentDidMount() {


  }

  render() {
    return (
      <div style={{flex:1}}>
        <canvas style={{height:'px !important'}} id="line-chart" width="100%" ></canvas>
      </div>
    )
  }
}

function mapStateToProps(state) {
  return {
    'mapData' : state.mapData,
    'chartData': state.chartData
  }
}

function mapDispatchToProps(dispatch) {
  return {

  }
}

export default connect(
  mapStateToProps, mapDispatchToProps
)(ChartComp)

我檢查了道具,一切都很好,每次更新時都會收到更長的Array,但是由於某種原因,它不會觸發組件的重新渲染。

我希望你們中的一個比我有更多的經驗,可以為我指明正確的方向,

這是減速器:

let initalState ={
  mapData: [],
  chartData: []
}

const rootReducer = (state = initalState, action) => {
  switch (action.type) {
    case "UPDATE-CHART":
      return Object.assign({}, state, { chartData: action.payload });
      break;
    case "UPDATE-MAP":
      return Object.assign({}, state, { mapData: action.payload });
      break;
    default:
      return state
  }
}

export default rootReducer;

在評論中提及了此問題,但由於它已解決了問題,因此將正式添加為答案。

看來您可能在動作創建者或減速器中的某個地方對this.props.chartData進行了this.props.chartData ,並且由於this.props.chartData仍指向同一列表(現在都更長了),因此響應未更新。 我建議嘗試使用Object.assign({}, state, { chartData: action.payload.slice() }); 在減速器中復制列表。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM