Правильный способ отображения отформатированных JSON данных из остальных API с помощью React - PullRequest
0 голосов
/ 20 марта 2020

У меня есть некоторые данные из API (Lambda / Node JS), поступающие в мое приложение React. Как отобразить разрывы строк и, возможно, некоторые элементы html, например <ul><li></li></ul> et c. Я пытался \n для разрывов строк.

Пока мой код выглядит следующим образом:

NodeJS

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;

Любая идея.

Ответы [ 2 ]

2 голосов
/ 20 марта 2020

Вы можете использовать prop dangerouslySetInnerHTML для рендеринга HTML и стиля { 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" }}
    />
  );
}
1 голос
/ 20 марта 2020

используйте это для новой строки ниже кода, динамически генерируйте div после погружения {"\ n"}. Проверьте это .. Просто проверьте, установлен ли awsApiData в состояние или нет. надеюсь, что это сработает. В основном вам нужно использовать функцию "map" {

 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>
    );
}

}

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...