首页 > 解决方案 > 我应该在哪里调用一个方法来使用它的数据?

问题描述

我想调用getAlbums()方法,以便我可以使用 get 请求中的数据并在客户端显示相册数据。我不知道在哪里调用它。我试图调用它,render()但它会创建一个无限循环。

相册.js

import React, { Component } from "react";
import { useParams } from "react-router-dom";
import axios from "axios";
import AlbumCard from "./AlbumCard";

export class Albums extends Component {
  constructor(props) {
    super(props);

    this.state = { albums: [] };
    this.getAlbums = this.getAlbums.bind(this);
  }

  async getAlbums() {
    const {
      match: { params },
    } = this.props;
    console.log(params.id);
    try {
      const res = await axios.get(
        `http://localhost:4000/albums/${encodeURIComponent(params.id)}`,
        {
          params: {
            id: params.id,
          },
        }
      );
      console.log(`Returned album data from the server: ${res}`);
      this.setState({ albums: res.data });
    } catch (err) {
      console.log(err);
    }
  }

  render() {
    return (
      <>
        <div className="container" style={{ color: "white" }}>
          hello
        </div>
      </>
    );
  }
}

export default Albums;

我想在 div 里面做这样的事情。

this.state.albums.map((album) => (<AlbumCard img={album.img}/>))

标签: javascriptreactjs

解决方案


你得到一个无限循环的原因是你在渲染中调用 setState。以下是幕后发生的事情:

1.getAlbums在render方法中调用。

2.功能触发setState

3.setState 导致重新渲染。

4.在render方法中,再次调用getAlbums。

无限重复1-4!

这是你可以做的:

  1. 创建一个按钮并getAlbums作为方法绑定到 onClick 事件处理程序。

2.getAlbums像这样在 ComponentDidMount 上运行:

  componentDidMount() {
      this.getAlbums();
    }

推荐阅读