搜尋

首頁  >  問答  >  主體

類型錯誤:無法讀取 null 的屬性(讀取“長度”)。這是什麼意思?

我有一個問題,我試著解決。無法讀取 null 的屬性(讀取“轉換”)。這是什麼意思? 。 我從這個問題中檢查了整合 mychart.update() 的選項 https://github.com/chartjs/Chart.js/issues/5149。 但是當我嘗試啟動時出現其他錯誤。

TypeError: Cannot read properties of null (reading 'length')
    at Object.acquireContext (Chart.js?473e:7756:1)
    at Chart.construct (Chart.js?473e:9324:1)
    at new Chart (Chart.js?473e:9311:1)
    at VueComponent.draw (Analytics-test.vue?b2a7:69:1)
    at VueComponent.loadTrainings (Analytics-test.vue?b2a7:444:1)
    at async VueComponent.mounted (Analytics-test.vue?b2a7:476:1)

在下面您可以看到我嘗試啟動的最後一個程式碼。

<template>
  <div> Прибыль/посещаемость <div class="small">
      <canvas id="mychart" height="400"></canvas>
    </div>
  </div>
</template>

<script>
import Chart from 'chart.js'
export default {
  data: () => ({
    flagStartDate: false,
    chartData: null,
    labels: [],
    dataset: {},
    draftData: null,
    data: [],
    datacollection: [],
    clubsId: ['5c3c5e12ba86198828baa4a7', '5c3c5e20ba86198828baa4c5', '60353d6edbb58a135bf41856', '61e9995d4ec0f29dc8447f81', '61e999fc4ec0f29dc844835e'],
    // clubsId: ['5c3c5e12ba86198828baa4a7', '61e999fc4ec0f29dc844835e'],
    // clubsId: ['61e999fc4ec0f29dc844835e'],
  }),
  methods: {

    draw() {
      if (this.mychart) {
        this.mychart.destroy();
      }
      const ctx = document.getElementById('main-chart');
      this.mychart = new Chart(ctx,
        {
          type: 'line',
          data: {
            labels: this.labels,
            datasets: this.datacollection
          },
          options: {
            responsive: true,
            elements: {
              line: {
                tension: 0 // disables bezier curves
              }
            },

            scales: {
              xAxes: [{
                type: "time",
                display: true,
                scaleLabel: {
                  display: true,
                  labelString: 'Time'
                },
                ticks: {
                  major: {
                    fontStyle: "bold",
                    fontColor: "#FF0000"
                  }
                }
              }],
              yAxes: [{
                display: true,
                scaleLabel: {
                  display: true,
                  labelString: this.labelY
                },
                ticks: {
                  min: 0, // it is for ignoring negative step.
                  beginAtZero: true,
                  stepSize: 1  // if i use this it always set it '1', which look very awkward if it have high value  e.g. '100'.
                }
              }]
            }
          }

        });
    },

    participantsCountClub(clubId) {
      switch (clubId) {
        case '5c3c5e12ba86198828baa4a7':
          return { label: "Тренировок на Фрунзенской", borderColor: "#3e95cd", fill: false }
        case '5c3c5e20ba86198828baa4c5':
          return { label: "Тренировок на Чернышевской", borderColor: "#8e5ea2", fill: false };
        case '60353d6edbb58a135bf41856':
          return { label: "Тренировок на Василеостровской", borderColor: "#e8c3b9", fill: false };
        case '61e9995d4ec0f29dc8447f81':
          return { label: "Тренировок на Московской", borderColor: "#3cba9f", fill: false };
        case '61e999fc4ec0f29dc844835e':
          return { label: "Тренировок на Лесной", borderColor: "#c45850", fill: false };
        default:
          return 'Неизвестный клуб';
      }
    },

    async loadTrainings(clubsId) {
      try {
        for (let clubId in clubsId) {
          clubId = clubsId[clubId]
          let dateFrom = '2021-06-01T00:00:00'
          let dateTo = '2022-08-01T23:59:59'
          let groupBy = 'month'
          await this.$store.dispatch('loadAvgSchedule', { clubId, dateFrom, dateTo, groupBy })
          this.draftData = this.$store.state.avgShedule
          if (this.labels.length === 0) {
            this.getDatesAvgIncome()
          }
          this.flagStartDate = true
          await this.getParticipantsCount(clubId)
          this.flagStartDate = false
        }
        this.draw()
        } catch (e) {
        console.error(e)
      }
    },

    async getParticipantsCount(clubId) {
      for (let item in this.draftData) {
        let positionDate = this.labels.indexOf(this.draftData[item].date.slice(0, 7))
        if (this.flagStartDate && positionDate > 0) {
          let zerroArray = await this.bindDataDates(positionDate)
          this.data = this.data.concat(zerroArray)
        }
        this.data.push(this.draftData[item].participantsCount)
        this.flagStartDate = false
      }
      this.dataset.data = this.data
      Object.assign(this.dataset, this.participantsCountClub(clubId))
      this.datacollection.push(this.dataset)
      console.log('this.datacollection', this.datacollection)
      this.data = []
      this.dataset = {}
    },

  },

  async mounted() {
    await this.loadTrainings(this.clubsId)
    
  },

  }
</script>

<style>
.small {
  max-width: 600px;
  margin: 150px auto;
}
</style>

我也嘗試了這個選項(使用 update()):

<template>
  <div> Прибыль/посещаемость <div class="small">
      <canvas id="mychart" height="400"></canvas>
    </div>
  </div>
</template>

<script>
import Chart from 'chart.js'
export default {
  data: () => ({
    flagStartDate: false,
    chartData: null,
    labels: [],
    dataset: {},
    draftData: null,
    data: [],
    datacollection: [],
    clubsId: ['5c3c5e12ba86198828baa4a7', '5c3c5e20ba86198828baa4c5', '60353d6edbb58a135bf41856', '61e9995d4ec0f29dc8447f81', '61e999fc4ec0f29dc844835e'],
    // clubsId: ['5c3c5e12ba86198828baa4a7', '61e999fc4ec0f29dc844835e'],
    // clubsId: ['61e999fc4ec0f29dc844835e'],
  }),
  methods: {

    draw() {
      if (this.mychart) {
        this.mychart.destroy();
      }
      const ctx = document.getElementById('main-chart');
      this.mychart = new Chart(ctx,
        {
          type: 'line',
          data: {
            labels: this.labels,
            datasets: this.datacollection
          },
          options: {
            responsive: true,
            elements: {
              line: {
                tension: 0 // disables bezier curves
              }
            },

            scales: {
              xAxes: [{
                type: "time",
                display: true,
                scaleLabel: {
                  display: true,
                  labelString: 'Time'
                },
                ticks: {
                  major: {
                    fontStyle: "bold",
                    fontColor: "#FF0000"
                  }
                }
              }],
              yAxes: [{
                display: true,
                scaleLabel: {
                  display: true,
                  labelString: this.labelY
                },
                ticks: {
                  min: 0, // it is for ignoring negative step.
                  beginAtZero: true,
                  stepSize: 1  // if i use this it always set it '1', which look very awkward if it have high value  e.g. '100'.
                }
              }]
            }
          }

        });
    },

    participantsCountClub(clubId) {
      switch (clubId) {
        case '5c3c5e12ba86198828baa4a7':
          return { label: "Тренировок на Фрунзенской", borderColor: "#3e95cd", fill: false }
        case '5c3c5e20ba86198828baa4c5':
          return { label: "Тренировок на Чернышевской", borderColor: "#8e5ea2", fill: false };
        case '60353d6edbb58a135bf41856':
          return { label: "Тренировок на Василеостровской", borderColor: "#e8c3b9", fill: false };
        case '61e9995d4ec0f29dc8447f81':
          return { label: "Тренировок на Московской", borderColor: "#3cba9f", fill: false };
        case '61e999fc4ec0f29dc844835e':
          return { label: "Тренировок на Лесной", borderColor: "#c45850", fill: false };
        default:
          return 'Неизвестный клуб';
      }
    },

    async loadTrainings(clubsId) {
      try {
        for (let clubId in clubsId) {
          clubId = clubsId[clubId]
          let dateFrom = '2021-06-01T00:00:00'
          let dateTo = '2022-08-01T23:59:59'
          let groupBy = 'month'
          await this.$store.dispatch('loadAvgSchedule', { clubId, dateFrom, dateTo, groupBy })
          this.draftData = this.$store.state.avgShedule
          if (this.labels.length === 0) {
            this.getDatesAvgIncome()
          }
          this.flagStartDate = true
          await this.getParticipantsCount(clubId)
          this.flagStartDate = false
        }
        // Below I tried refresh charts after updates data
        this.mychart.update() 
        } catch (e) {
        console.error(e)
      }
    },

    async getParticipantsCount(clubId) {
      for (let item in this.draftData) {
        let positionDate = this.labels.indexOf(this.draftData[item].date.slice(0, 7))
        if (this.flagStartDate && positionDate > 0) {
          let zerroArray = await this.bindDataDates(positionDate)
          this.data = this.data.concat(zerroArray)
        }
        this.data.push(this.draftData[item].participantsCount)
        this.flagStartDate = false
      }
      this.dataset.data = this.data
      Object.assign(this.dataset, this.participantsCountClub(clubId))
      this.datacollection.push(this.dataset)
      console.log('this.datacollection', this.datacollection)
      this.data = []
      this.dataset = {}
    },

  },

  async mounted() {
    await this.loadTrainings(this.clubsId)
    this.draw()
  },

  }
</script>

<style>
.small {
  max-width: 600px;
  margin: 150px auto;
}
</style>

當我在偵錯器中打開字串時:

您可以看到對此行的參考:

如果檢查最後一個參考:

你可以看到這一行:

P粉031492081P粉031492081388 天前749

全部回覆(2)我來回復

  • P粉851401475

    P粉8514014752023-11-05 10:04:31

    屬性 length 是針對 Array 的,錯誤表明無法讀取 length 的 null(重要的是“null”這個詞),因此問題是具有該屬性的 const 或 var 出於任何原因變為 null。

    回覆
    0
  • P粉071626364

    P粉0716263642023-11-05 00:11:54

    問題出在模板。 我忘記為畫布寫入正確的 ID。 一定是這樣:

    <canvas id="main-chart" height="400"></canvas>

    回覆
    0
  • 取消回覆