繁体   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