我正在使用 MongoDB 服务器在 Node API 上发送 GET 请求。我收到了对象格式数组中 JSON 格式的响应。我想在列表中显示所有这些结果。现在我正在制作这样的函数
class VendorDashboard extends React.Component {
constructor() {
super();
this.state = {
paginationValue: '86',
title: ""
}
this.handleLogout = this.handleLogout.bind(this);
this.gotoCourse = this.gotoCourse.bind(this);
}
componentDidMount() {
axios.get('/vendor/showcourses') //the api to hit request
.then((response) => {
console.log(response);
let course = [];
course = response.data.map((courseres) => {
this.setState({
title: courseres.title
});
})
});
现在发生的情况是它只显示一个结果。我想显示该 api 上的所有结果。我该怎么做?
最佳答案
这里的这一部分覆盖了每门类(class)的标题。
course = response.data.map((courseres) => {
this.setState({
title: courseres.title
});
})
您可以将状态保留为标题数组并执行此操作;
course = response.data.map((courseres) => {
return courseres.title;
})
this.setState({titles: course});
然后您可以重复组件中的标题数组。 就像在渲染方法中一样;
const { titles } = this.state;
return <div>{titles.map((title, index) => <div key={index}>{title}</div>)}</div>
关于JavaScript/ReactJS : Show results from backend in a list,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49550667/