下面是我的ReactJS组件的代码片段,我试图将输出旁边带有按钮的按钮以列表格式放置。在“ axios” get函数中接收到的输出来自一个api,格式为: [{'name':'i-cc608f4d'},{'name':'i-fd608f7c'} ,{'name':'i-fe608f7f'}] 我想用一个按钮列出这些ID。
import React, { Component } from "react";
import axios from "axios";
const pStyle = {
backgroundColor: "#79D3EF",
color: "white"
};
export default class CityContent extends Component {
constructor(props) {
super(props);
this.state = {
citydetail: []
};
}
componentDidMount() {
axios.get("http://127.0.0.1:8000/Delhi").then(res => {
const citydetail = res.data;
this.setState({ citydetail });
});
}
render() {
return (
<div className="content-wrapper">
<section className="content-header">
<div className="row">
<div className="col-md-4">
<div className="box">
<div className="box-body">
<div className="row">
<div className="col-md-8">
<ul>{this.state.citydetail.state}</ul>
</div>
</div>
</div>
</div>
</div>
</section>
</div>
);
}
我应该写些什么来替换{this.state.citydetail.state}
。
因为当前,它正在打印API输出本身。
答案 0 :(得分:0)
<div className="col-md-8">
<ul>
{
this.state.citydetail.map((city) => (
<li>{city.name}<button>Click</button></li>
)}
</ul>
</div>
此代码将打印您的输出,地图将通过citydetail数据及其旁边的按钮进行映射。
答案 1 :(得分:0)
应该是这样的
<ul>
{
this.state.citydetail.map((city, index) => (
<li key={index}>{city.name}<button>{city.name}</button></li>
)}
</ul>
更新
在componentDidMount()
this.setState({ citydetail : citydetail });
更新2(在OP评论之后)
我无法更改此输出的格式...
尝试
axios.get("http://127.0.0.1:8000/Delhi").then(res => {
const citydetail = res.data;
let arrData = JSON.parse(citydetail.replace(/'/g, '"'));
this.setState({ citydetail: arrData });
});