react.js-为什么渲染两次

时间:2020-04-26 19:43:58

标签: reactjs api axios console.log

我正在尝试从数组中获取一个值。问题是价值渲染了两次。第一次获得不确定的值,但第二次似乎还可以。我在哪里错过? 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>
    );
  }
}

2 个答案:

答案 0 :(得分:1)

这里发生了无数问题,导致您出现问题的两个主要问题是:

  1. 您可以使用class属性设置默认状态,然后立即在类构造函数中将其清除(这实际上意味着info的默认状态为undefined)。
  2. 您默认在每个渲染上将values设置为undefined,当组件首次渲染时this.state.infoundefined,因此values仍为undefined然后继续在mySeries中进行设置,然后随后在用户界面中进行渲染。

如果您不想在拥有某些东西之前进行渲染,请渲染一个占位符组件,例如

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

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

答案 1 :(得分:0)

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

因此它呈现两次。

只有在定义了pluginInfo在第二个渲染器上时,您才可以设置值。