react.js - 为什么渲染两次

react.js - why rendering two times

我正在尝试从数组中获取值。问题是价值被渲染了两次。第一次得到未定义的值,但第二次似乎没问题。我错过了哪里? Please see the console result in screenshot

import React, { Component } from "react";
import axios from "./axios";
import ZingChart from "zingchart-react";

export default class Chart extends Component {
  state = {
    info: [],
  };

  componentDidMount() {
    axios
      .get(
        `https://api.wordpress.org/plugins/info/1.0/3r-elementor-timeline-widget.json/`
      )
      .then((res) => {
        this.setState({ info: res.data });
      });
  }

  constructor(props) {
    super(props);

    this.state = {
      config: {
        type: "bar",
      },
    };
  }

  render() {
    var values;
    const pluginInfo = this.state.info;
    if (pluginInfo !== undefined) {
      const ratings = Object.values(pluginInfo.ratings);
      values = ratings;
    }
    //var mySeries = [{ values: [1, 3, 8] }];
    var mySeries = [{ values: values }];
    console.log(mySeries); // 1st time get undefined array but 2nd time is ok. 

    return (
      <div>
        <ZingChart data={this.state.config} series={mySeries} />
      </div>
    );
  }
}

因为它渲染组件然后进入 componentDidMount 并调用您的 axios 函数,这是一个异步请求。然后它在 x 时间后解析异步请求并设置触发重新渲染的状态。

因此它渲染了两次。

如果 pluginInfo 在第二个渲染器上定义了,那么您只是在设置值。

这里有无数的问题,导致你的问题的两个主要问题是:

  1. 您使用 class 属性 设置默认状态,然后立即在 class 构造函数中将其清除(这实际上意味着 infoundefined).
  2. 您在每次渲染时默认将 values 设置为 undefined,当组件首次渲染时 this.state.infoundefined 因此 values 仍然是 undefined 然后你继续在 mySeries 中设置它,然后在 UI.
  3. 中呈现

如果你不想在你有东西之前渲染,渲染一个占位符组件来代替,例如

if (!values) return <p>Loading...</p>;

return (...) // render component with mySeries etc.