简体   繁体   English

将 .then() 内部的解析字符串作为 JSX 元素导出到外部

[英]get parse String inside .then() to outside as JSX element

In react I import these following libraries在反应中,我导入了以下这些库

import React from "react";
import {
  Container,
  Row,
  Col,
  Card,
  CardBody,
  CardFooter,
  Badge,
  Button
} from "shards-react";

inside the functions, I have the following fetch method and inside .then() I add JSX elements在函数内部,我有以下 fetch 方法,在 .then() 中我添加 JSX 元素

     output=''
fetch(
          "https://api.rss2json.com/v1/api.json?rss_url=https://medium.com/feed/@MediumStaff"
        )
          .then(res => res.json())
          .then(data => {
            const res = data.items; 

            let a = 0;
            res.forEach(item => {

              if (a === 0 || a === 3 || a === 6 || a === 9) {
                output += `<Row>`;
              }

              output += `<Col lg="6" md="6" sm="12" className="mb-4">
                <Card small className="card-post card-post--1">
                  <div
                    className="card-post__image"
                    style={{ backgroundImage: "url("+"${item.thumbnail}"+")" }}
                  >
                  </div>
                  <CardBody>
                  //JSX elements
                  </CardBody>
                </Card>
                </Col>`;
              if (a === 2 || a === 5 || a === 8 || a === 9) {
                output += `</Row>`;
              }

              a += 1;
            });

            document.querySelector(".blog__slider").innerHTML = output;
            console.log(output);

          });

In return I used the following code作为回报,我使用了以下代码

<div className="blog__slider"></div>

I thought the functional component in React did not take output values as JSX components.我认为 React 中的功能组件没有将输出值作为 JSX 组件。 If I get update output value outside of .then() I could use dangerouslySetInnerHTML={{__html: output}}如果我在.then()之外获得更新输出值.then()我可以使用dangerouslySetInnerHTML={{__html: output}}.then() dangerouslySetInnerHTML={{__html: output}}

create a class component and add an array state inside the constructor of that class component.创建一个类组件并在该类组件的构造函数中添加一个数组状态。 because when the class created that state will initiate.因为当该类创建时,该状态将启动。 Using React Life cycle method componentDidMount fetch the JSON objects and push the JSON objects into the array state then you can use the JSX element in the render method使用 React 生命周期方法 componentDidMount 获取 JSON 对象并将 JSON 对象推送到数组状态,然后您可以在渲染方法中使用 JSX 元素

codesandbox.io/s/twilight-breeze-plbby codeandbox.io/s/twilight-breeze-plbby

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM