0

这就是我所说的动态组件(从其余 API 获取数据的组件)

import React from "react";
import axios from "axios";

class WeatherData extends React.Component {
  state = {
    data: null,
    latitude: "19.970324",
    longitude: "79.303360",
    weatherData: {},
    _apiKey: "", //NOTE: In my code I have pass the Id here.
    city: "chandrapur,in"
  };
  componentDidMount() {
    const { latitude, longitude, _apiKey, city } = this.state;
    axios
      .get(
        `https://cors-anywhere.herokuapp.com/https://samples.openweathermap.org/data/2.5/weather?lat=${latitude}&lon=${longitude}&appid=${_apiKey}`
      )
      .then(res => {
        this.setState({ weatherData: res.data }, () => {});
      });
  }
  render() {
    return (
      <div>
        {this.state.weatherData.weather &&
          this.state.weatherData.weather !== null &&
          this.state.weatherData.weather.map(obj => {
            return (
              <div key={obj.id}>
                {/* <span> */}
                id: {this.state.weatherData.weather[0].id}
                <br />
                main: {this.state.weatherData.weather[0].main}
                <br />
                discription: {this.state.weatherData.weather[0].description}
                <br />
                icon: {this.state.weatherData.weather[0].icon}
                {/* </span> */}
              </div>
            );
          })}
      </div>
    );
  }
}

export default WeatherData;

当我试图在“renderToString”中传递这个组件时,我得到一个空值

我想知道如何让这段代码连同我从其他 API 获得的值一起进入字符串。

注意:当我尝试在“renderToString”中传递地图组件时,它给出的是“正在加载...”而不是带有数据的组件。所以我觉得这是一个时间问题。

我正在尝试访问它。我在 onClick 事件处理程序中调用 print 。

const print = () => {
  const string = ReactDOMServer.renderToString(<WeatherData />);
  const pdf = new jsPDF("p", "mm", "a4");

  pdf.fromHTML(string);
  pdf.save("pdf");
};
4

0 回答 0