javascript - 我应该在哪里调用一个方法来使用它的数据?
问题描述
我想调用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}/>))
解决方案
你得到一个无限循环的原因是你在渲染中调用 setState。以下是幕后发生的事情:
1.getAlbums
在render方法中调用。
2.功能触发setState
。
3.setState 导致重新渲染。
4.在render方法中,再次调用getAlbums。
无限重复1-4!
这是你可以做的:
- 创建一个按钮并
getAlbums
作为方法绑定到 onClick 事件处理程序。
2.getAlbums
像这样在 ComponentDidMount 上运行:
componentDidMount() {
this.getAlbums();
}
推荐阅读
- javascript - 使用脚本在 laravel 中使用模态形式更新/编辑
- django - 如何让 Django 应用在 Heroku 上运行,使用 Heroku Scheduler 执行计划作业
- jsf - 如何在 JSF 中制作类似于 Google 的搜索结果?
- c# - 使用动态变量获取 Json 值
- angular - Angular中的文化路线参数
- c++ - Visual Studio 2019 从 Github 源代码编译 DLL - 双簧管
- javascript - 以正确的方式删除事件侦听器
- docker - 无法从 Kubernetes 主节点访问服务
- php - 如何从 DOM 输出中删除重复值?
- python - 船不动,python速成班第12章