如何在React JS中将列表输出动态打印为按钮



下面是我的ReactJS组件的代码片段,我试图将旁边有一个按钮的输出放在列表格式中。在"axios"get函数中接收到的输出来自一个api,其格式如下:[{‘name’:‘i-cc608f4d’},{‘ame’:‘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输出本身。

<div className="col-md-8">
<ul>
{
this.state.citydetail.map((city) => (
<li>{city.name}<button>Click</button></li>
)}
</ul>
</div>

这个代码将打印你的输出,地图将通过城市细节的数据和旁边的按钮绘制

它应该类似于这个

<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 });
});

最新更新