Vai*_*edi 2 javascript api json html-table reactjs
我正在使用一个 API,它返回各种不同键值对的 JSON。我试图将它们显示为render()一个包含 2 列(键和值)的表,其中分别包含对象键和值。
fetchBasicDetails()是 POST,它采用默认的 this.state 值作为输入并返回 JSON 输出。setState属性中。<table>使用 Object.keys 显示标签中的对象数据forEach,但什么也没有显示。任何帮助表示赞赏。谢谢。
export default class HoroscopeReport extends React.Component {
constructor(props) {
super(props);
this.state = {
day: 11,
month: 2,
year: 2019,
hours: 12,
minutes: 59,
tzone: 5.5,
lat: 19.22,
lon: 25.2,
birth_details:{}
};
}
handleSubmit = event => {
event.preventDefault();
//console.log("Received user submitted data"+JSON.stringify(this.state))
this.fetchBasicDetails();
};
fetchBasicDetails() {
let myHeaders = new Headers();
myHeaders.append("Content-Type", "application/x-www-form-urlencoded");
myHeaders.append("Authorization", "Basic XXXXXXXXXXXXXXX");
let urlencoded = new URLSearchParams();
urlencoded.append("day", this.state.day);
urlencoded.append("month", this.state.month);
urlencoded.append("year", this.state.year);
urlencoded.append("hour", this.state.hours);
urlencoded.append("min", this.state.minutes);
urlencoded.append("lat", this.state.lat);
urlencoded.append("lon", this.state.lon);
urlencoded.append("tzone", this.state.tzone);
let requestOptions = {
method: 'POST',
headers: myHeaders,
body: urlencoded,
redirect: 'follow'
};
fetch("https://json.astrologyapi.com/v1/birth_details", requestOptions)
.then(response => response.text())
.then(result => {
this.setState({ birth_details: result });
})
.catch(error => console.log('error', error));
}
render() {
return (
<div>
{/* FORM SUBMITTION CODE HERE */}
<h2>Output:-</h2>
<table border={2} cellPadding={5}>
<thead>
<tr>
<td>Key</td>
<td>Value</td>
</tr>
</thead>
<tbody>
Object.keys(this.birth_details).forEach(function (element) {
return <tr><td>element</td><td>this.birth_details[element]</td></tr>;
});
</tbody>
</table>
</div>
);
}
}
Run Code Online (Sandbox Code Playgroud)
作为参考,这是 JSON 的输出:-
{"year":2019,"month":2,"day":11,"hour":12,"minute":59,"latitude":19.22,"longitude":25.2,"timezone":5.5,"gender":" ","name":" ","seconds":0,"ayanamsha":24.124044280610406,"sunrise":"10:19:50","sunset":"21:47:13"}
Run Code Online (Sandbox Code Playgroud)
通常,React 中基于数组的渲染元素是使用map()而不是 来处理的forEach()。原因是map()您可以在迭代的同时操作每个元素并返回完全适合方法的JSX语法render。同时forEach()不返回任何内容,仅返回undefined.
我想你可以尝试以下方法:
render() {
return (
<div>
<h2>Output:-</h2>
<table border={2} cellPadding={5}>
<thead>
<tr>
<td>Key</td>
<td>Value</td>
</tr>
</thead>
<tbody>
{
this.state.birth_details &&
Object.keys(this.state.birth_details).map(function (element) {
return <tr>
<td>{element}</td>
<td>{this.state.birth_details[element]}</td>
</tr>;
});
}
</tbody>
</table>
</div>
);
}
Run Code Online (Sandbox Code Playgroud)
我希望这有帮助!
| 归档时间: |
|
| 查看次数: |
15546 次 |
| 最近记录: |