我应该在哪里调用方法来使用其中的数据?



我想调用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

2.该功能触发setState

3.设置状态导致重新渲染。

4.In 呈现方法,将再次调用 getAlbums。

无限重复1-4!

以下是您可以执行的操作:

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

2.在组件安装上运行getAlbums,如下所示:

componentDidMount() {
this.getAlbums();
}

componentDidMount((是发出 AJAX 请求的最佳位置。

componentDidMount(( 方法将在 AJAX 调用获取数据后设置状态。当数据可用时,它会导致 render(( 被触发。

这是 componentDidMount(( 的工作示例

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: [] }
}
componentDidMount() {
axios.get( 
`http://localhost:4000/albums/${encodeURIComponent(this.props.id)}`,
{ params: { id: this.props.id } }
)
.then(response => {
console.log(`Returned album data from the server: ${res}`)
this.setState({ albums: response.data })
}
)
.catch(e => {
console.log("Connection failure: " + e)
}
)
}
render() {
return (
<div>
{/*   Code for {this.state.albums.map(item => )}  */}
{/*   render() method will be called whenever state changes.*/}
{/*   componentDidMount() will trigger render() when data is ready.*/}
</div>
)
}
}
export default Albums

更多信息:

https://blog.logrocket.com/patterns-for-data-fetching-in-react-981ced7e5c56/

use componentDidMount((

componentDidMount(){
getAlbums() 
}

最新更新