如何在“ renderToString”中传递动态组件以将其转换为字符串

时间:2019-11-21 17:46:50

标签: reactjs react-router jspdf jspdf-autotable render-to-string

这就是我所说的动态组件(从其余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");
};

0 个答案:

没有答案