json - 从 API react 输出 JSON

标签 json node.js api reactjs npm

我已经设法从我创建的 api 获取 JSON,但是我在实际渲染该 JSON 时遇到了麻烦。我已经设法通过“stringify”将其输出到控制台中,但是我似乎无法实际将 JSON 渲染到页面。

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

function getData() {
  return $.ajax({
    type: "GET",
    url: 'http://localhost:3001/data',
    data: {},
    xhrFields: {
      withCredentials: false
    },
    crossDomain: true,
    dataType: 'json',
    success: handleData
  });
}
function handleData(data /* , textStatus, jqXHR */ ) {
  console.log(JSON.stringify(data));
  return JSON.stringify(data);
}

class App extends Component {
  render() {
    return (
      <div className="App">
        <header>
          <h2>Last Application Deployment </h2>
        </header>
        <div id='renderhere'>
          {JSON.stringify(getData().done(handleData))}
        </div>
      </div>
    );
  }
}

export default App;

最佳答案

你不能在 return 中执行 render 方法中的函数。你可以使用 React 生命周期并将结果存储在这样的状态中 =>

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'>
              {this.state.result && and what you want because i dont                                  know why you want use JSON.stringfy - you use .map() or ...}
            </div>
          </div>
        );
      }
    }

我建议你看看this文章和this .

关于json - 从 API react 输出 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39827387/

相关文章:

javascript - Jquery .ajax 获取 json 响应请求

python - 无法使用 Python xmlrpc 在 aria2 中添加选项?

ruby-on-rails - 如何正确格式化 json 以使用 RestClient 发送

javascript - Express .post 路由方法未定义

javascript - 有人可以使用我的 api key 对我的 YouTube channel 进行 CRSF 攻击吗?

json - 尝试解析 JSON 值时出错

node.js - 将对象的更新从客户端发送到 nodejs

node.js - 使用 PassportJS 在 Session 中修改 user.username

javascript - google maps API v3 如何删除信息窗口矩形下的箭头?

c# - 从复杂的 JSON 对象创建 C# 类,其中动态变量是类名