【问题标题】:React output JSON on new line在新行上反应输出 JSON
【发布时间】:2016-10-03 10:19:14
【问题描述】:

我已经设法从 API 输出 JSON,但是它是在一个大块中输出的,但是我希望每次有一个关闭的 '}' 时都在一个新行上显示每一块 json。

import React, { Component } from 'react';
import './App.css';
import $ from 'jquery';

class App extends Component {

  state = {result : null}

  componentDidMount = () => {

    $.ajax({
      type: "GET",
      url: 'http://localhost:3001/data',
      data: {},
      xhrFields: {
        withCredentials: false
      },
      crossDomain: true,
      dataType: 'JSON',
      success: (result) => {
        this.setState({result : result});
      }
    });

  };

  render() {
    return (
          <div className="App">
            <header>
              <h2>Last Application Deployment </h2>
            </header>
            <div id='renderhere'>
              {JSON.stringify(this.state.result)}
            </div>
          </div>
        );
  }
    }

export default App;

【问题讨论】:

    标签: json api reactjs


    【解决方案1】:

    第一个选项:如果你想输出 JSON 用于调试目的,你应该尝试react-json-pretty

    第二个选项:如果您尝试做的事情应该用于生产,请执行以下操作:

    <div id='renderhere'>
      <pre>{JSON.stringify(this.state.result, null, 2)}</pre>
    </div>
    

    【讨论】:

    • 谢谢你的回答,但是,我已经在使用JSON.stringify(),我想要实现的是,我希望 JSON 中的每个对象都不是输出整个块,而不是输出整个块在新行上输出到浏览器,如果不清楚,请见谅。
    • 对不起,我的代码示例被破坏了,请再次检查答案。
    • 太好了!谢谢。
    【解决方案2】:

    尝试围绕这种 css 样式包装您的文本。你的问题将得到解决。不需要复杂的函数。

     <p style={{whiteSpace: 'pre-line'}}>my json text goes here \n\n</p>
    

    【讨论】:

      猜你喜欢
      • 2022-09-23
      • 2014-03-02
      • 2014-08-15
      • 2016-07-22
      • 2017-05-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多