我有这段代码可以使用Axios
从远程获取类别,并且我想在单击按钮后在弹出窗口中列出这些类别的名称:
import React, { Component } from "react";
import axios from "axios";
import Button from 'react-bootstrap/Button';
import Popup from "reactjs-popup";
class CategoryView extends Component {
constructor(props) {
super(props);
this.state = {
catN: [],
};
}
componentDidMount() {
this.getCategories(this.state.categoryData.catN);
}
// fetch all categories
getCategories() {
axios
.get("/v1/categories")
.then((res) => {
var cats = [],
catsN = [];
for (var i = 0; i < res.data.items.length; i++) {
cats[i] = res.data.items[i];
catsN[i] = cats[i].name;
}
console.log(res);
this.setState({
catN: catsN,
});
})
.catch((error) => console.log("Get Error"));
}
render() {
return (
<div>
<div>
<Popup trigger= {<Button variant="outline-primary">Add to Category</Button>}
modal
closeOnDocumentClick
>
<ul className="categorylist">
</ul>
<Button variant="primary" size="lg" block>
Show Categories
</Button>
</Popup>
</div>
<p
style={{
float: "left",
marginLeft: "30px",
marginRight: "20px",
}}
>
</p>
</div>
);
}
}
export default VideoView;
我的问题是我不知道如何在render方法中列出类别名称,console
对于get()
请求显示的内容类似于this。
如何呈现类别名称列表?
答案 0 :(得分:0)
由于catN是数组,因此可以使用map()
方法显示名称
{catN.length ? (
<ul>
{catN.map((ele) => (
<li>{ele}</li>
))}
</ul>
) : null}
答案 1 :(得分:0)
这是在反应中渲染待办事项数组的示例:
class Todos extends Component{
constructor(props){
super(props)
this.state={
todos:[{label:wake up ,completed:true}, {label : got to work, completed :false}]
}
return ( <div id="todo">
<ul>{this.state.todos.map(item=>(
<li>{item.label} {item.completed?"completed":"incomplete"}</li>
)</ul>
</div>)
}