繁体   English   中英

使用 React 显示来自 rest api 的格式化 JSON 数据的正确方法

[英]Correct way to display formatted JSON data from rest api with React

我有一些来自 api(Lambda/Node JS)的数据进入我的 React 应用程序。 如何显示换行符以及一些 html 元素,例如<ul><li></li></ul>等。我尝试使用\\n来换行。

到目前为止,我的代码如下:

节点

exports.handler = async (event) => {
    if (event.httpMethod === 'GET') {
        return getData(event);
    }
    console.log(getData);
};

const getData = event => {

    let data = {
        "home": [{
                "title": "Home",
                "body": "Lorem Ipsum is simply dummy text of the printing and typesetting industry.\nLorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.", 
                "image": "https://via.placeholder.com/1280x600.jpg"
            }
        ],
        "about": [{
                "title": "About",
                "body": "Lorem Ipsum is simply dummy text of the printing and typesetting industry.\nLorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.", 
                "image": "https://via.placeholder.com/1280x600.jpg"
            }
        ],
         "work": [{
                "title": "Work",
                "body": "Lorem Ipsum is simply dummy text of the printing and typesetting industry.\nLorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.", 
                "image": "https://via.placeholder.com/1280x600.jpg"
            }
        ],
         "work_one": [{
                "title": "Work nested",
                "body": "Lorem Ipsum is simply dummy text of the printing and typesetting industry.\nLorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.", 
                "image": "https://via.placeholder.com/1280x600.jpg"
            }
        ]
    };

    return {
        statusCode: 200,
        headers: {
        "Access-Control-Allow-Origin" : "*", // Required for CORS support to work
        "Access-Control-Allow-Credentials" : true // Required for cookies, authorization headers with HTTPS
        },
        body: JSON.stringify(data, null, 2)
    };
};

反应组件

 import React, { Component } from 'react';
  import '../main/main.css';


  class Main extends Component {
     _isMounted = false;

    constructor() {
      super();
      this.state = {
        awsApiData: [],
        loading: false,
        errorMessage: ''
      };
    }

    componentDidMount() {
      this._isMounted = true;
      console.log('app mounted');
      this.setState({ loading: true});
      /*global fetch */
      fetch('https://onelbip0e6.execute-api.eu-west-2.amazonaws.com/xxxx')
        .then(data => data.json())
        .then(data => this.setState({ awsApiData: data, loading: false }, () => console.log(data)))
        .catch(err => { 
         this.setState({errorMessage: err.message});
        });

    }

        componentWillUnmount() {
        this._isMounted = false;
    }

    render() {
      const data = this.state.awsApiData;
      return (
        <div className="main-content container">
        {this.state.errorMessage &&
        <h3 className="error"> Error: { this.state.errorMessage } </h3> }
           {this.state.loading ? <div className="text-center">Loading...</div> : (data && data.home) &&
              <div><h2>{data.home[0].title}</h2><br /><p className="mb-5">{data.home[0].body}</p>
               <img className ="image" src={data.home[0].image} alt="alternative tag"></img> 
              </div>
          }    
      </div>
      );
    }
  }
  export default Main;

有任何想法吗。

您可以使用 prop dangerouslySetInnerHTML来呈现 HTML 和 style { whiteSpace: "pre-line" }来处理空格

这是一个工作示例: https : //codesandbox.io/s/cool-microservice-t5rbu

export default function App() {
  const text =
    "One \n Two \n Three <ul><li>first item</li><li>second item</li></ul>";
  return (
    <div
      dangerouslySetInnerHTML={{ __html: text }}
      style={{ whiteSpace: "pre-line" }}
    />
  );
}

使用此代码下面的新行在潜水后动态生成 div {"\\n"} 检查这个.. 只需检查 awsApiData 是否设置为状态。 希望这会奏效。主要是你必须使用“地图”功能{

 render() {
    const data = this.state.awsApiData;
    return (
        <div className="main-content container">
            {this.state.errorMessage &&
            <h3 className="error"> Error: { this.state.errorMessage } </h3> }
            {this.state.loading ? <div className="text-center">Loading...</div> :
                { this.state.awsApiData.home.map((item, index) => {
                        return (
                        <div><h2>{item.title}</h2><br /><p className="mb-5">{item.body}</p>
                            <img className ="image" src={data.home[0].image} alt="alternative tag"></img>
                        </div>
                        )
                })
                }
            }
        </div>
    );
}

}

暂无
暂无

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

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