我已经设法从我创建的 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>
);
}
}
关于json - 从 API react 输出 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39827387/