How can I pass dynamic component in a “renderToString” to convert into string

久未见 提交于 2021-02-11 17:44:50

问题


This is what I mean by the dynamic component (the component which is getting data from the rest 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;

When I am trying to pass this component in the "renderToString" I am getting an empty value

I want to know how can I make this code get into the string along with the value which I am getting from the rest API.

NOTE: When I tried to pass the map component in the "renderToString" it was giving "Loading..." rather than the component with data. So I feel it is a timing issue.

I am trying to access this. And I am calling print in an onClick event handler.

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

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

来源:https://stackoverflow.com/questions/58980868/how-can-i-pass-dynamic-component-in-a-rendertostring-to-convert-into-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!