JavaScript/ReactJS : Show results from backend in a list

标签 javascript node.js reactjs

我正在使用 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/

相关文章:

javascript - 浏览器后退按钮问题

javascript - 如何通过nodejs使用TypeScript编译器?

node.js - 我想使用 gitbash 在我的共享主机中安装 nodejs

javascript - 使用 Web Audio API 进行跨应用程序音频分析

javascript - Kineticjs DragBoundFunc 用于矩形中的矩形

node.js - 将node.js代码封装在函数中

javascript - React 状态从一个组件不一致地传递到下一个组件

reactjs - React 仅重新渲染一个 child

reactjs - 如果/否则将漂亮的格式重新格式化为单行

javascript - 为什么我的函数没有被调用?