【问题标题】:Why chart renders after second click - react-chartjs-2为什么图表在第二次点击后呈现 - react-chartjs-2
【发布时间】:2021-03-15 00:36:40
【问题描述】:

我使用 react-chartjs-2 在 React 应用程序中创建了一个图表。我在主页上有 2 个项目:“chart1”和“chart2”。当我单击“chart1”时 - 图表显示没有数据。第二次单击后,数据正​​确呈现。接下来我要渲染“chart2”,但点击该项目后,“chart1”会渲染。第二次单击后,“chart2”的数据正确呈现。 你知道是什么问题吗?我想在第一次点击后渲染每个图表。

Chart.js

import React, { useEffect, useState } from 'react';
import { connect } from 'react-redux';
import { Line } from 'react-chartjs-2';

import { getChartData } from '../../actions/sensors';

const Chart = (props) => {

  const [chartDataState, setChartDataState] = useState({});

  const createChart = () => {
    const id = props.match.params.id;
    props.getChartData(id);

    setChartDataState({
      labels: props.chartData.map(data => {
        const date = new Date(data.delivery_time).toLocaleDateString();
        const time = new Date(data.delivery_time).toLocaleTimeString();
        return `${time} | ${date}`;
      }),
      datasets: [
        {
          data: props.chartData.map(data => data.sensor_data),
          fill: false,
          backgroundColor: '#987316',
          borderColor: 'rgba(152, 115, 22, 0.2)',
        },
      ],
    })
  }

  useEffect(() => {
    createChart();
  }, [])

  return (  
    <div className="container">
      <div className="head" style={{'marginBottom': '30px'}}>
        <h2>Chart</h2>
        <div className="line" style={{"width": "900px"}}></div>
      </div>
      <div className="chart">
        <Line
          data={chartDataState}
          options={{
            maintainAspectRatio: false,
            legend: {
              display: false,
            }
          }}
          height={400}
        />
      </div>
    </div>
  );
}

const mapStateToProps = state => ({
  chartData: state.sensors.chartData,
})
 
export default connect(mapStateToProps, { getChartData })(Chart);

传感器(Redux 操作)

export const getChartData = id => (dispatch, getState) => {

  const token = getState().auth.token;

  const config = {
    headers: {
      'Content-Type': 'application/json',
      'Authorization': `Token ${token}`
    }
  } 

  axios.get(`${baseURL}/sensors_data/list/${id}`, config)
  .then(res => {
    dispatch({
      type: GET_CHART_DATA,
      payload: res.data
    })
  })
  .catch(err => console.log(err))
}

传感器(Redux 减速器)

import { GET_CHART_DATA } from '../actions/types';

const initialState = {
  chartData: [],
}

export default function(state = initialState, action) {
  switch(action.type) {
    case GET_CHART_DATA:
      return {
        ...state,
        chartData: action.payload
      }
    default:
      return state;
  }

【问题讨论】:

    标签: javascript reactjs chart.js


    【解决方案1】:

    当您第一次单击时,您会触发对数据的请求,但您的组件不会在呈现之前等待该数据。

    我建议在您的退货中添加一个条件。如果没有 Redux,我会这样做(我从未使用过 Redux)

    return (  
      <div className="container">
        <div className="head" style={{'marginBottom': '30px'}}>
          <h2>Chart</h2>
          <div className="line" style={{"width": "900px"}}></div>
        </div>
        <div className="chart">
          {chartDataState.length > 0 ? 
          <Line
            data={chartDataState}
            options={{
              maintainAspectRatio: false,
              legend: {
                display: false,
              }
            }}
            height={400}
          />
          : <div>Loading...</div>}
        </div>
      </div>
    );
    

    基本上:您不希望您的组件在数据返回之前呈现图表。

    【讨论】:

    • 现在“正在加载...”一直在渲染,我看不到任何图表
    • 条件(我放 ChartDataState.length > 0 的地方)需要基于状态或道具,当状态改变时会更新。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-03
    • 2023-03-14
    • 2022-11-22
    • 2021-11-03
    • 1970-01-01
    相关资源
    最近更新 更多