[英]Render an array in React JS using map
我有這段代碼使用Axios
從遠程獲取類別,我想在單擊按鈕后在彈出的 window 中列出這些類別的名稱:
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;
我的問題是我不知道如何在渲染方法中列出類別名稱, console
為get()
請求顯示了類似的內容。
如何呈現類別名稱列表?
由於 catN 是一個數組,因此可以使用map()
方法來顯示名稱
{catN.length ? (
<ul>
{catN.map((ele) => (
<li>{ele}</li>
))}
</ul>
) : null}
這是一個在 react 中渲染待辦事項數組的示例:
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>)
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.