我想更改API返回的页面数。所以我使用API来获取电影,我正在使用反应挂钩来做到这一点。我创建了一个单独的函数来使用useEffect从API中获取,但我不知道如何包含使用react钩子更改从API返回的页面的功能。
我不知道如何做到这一点。
class ContactList extends React.Component {
state = {
contacts: [],
per: 2,
page: 1,
totalPages: null
}
componentWillMount() {
this.loadContacts()
}
loadContacts = () => {
const {per, page, contacts} = this.state;
const url = `https://student-example-api.herokuapp.com/v1/contacts.json?per=${per}&page=${page}`;
fetch(url)
.then(response => response.json())
.then(json => this.setState({
contacts: [...contacts, ...json.contacts]
}));
}
loadMore = () => {
this.setState((prevState) => ({
page: prevState.page + 1
}), this.loadContacts)
}
render() {
return (
<div>
<ul className="contacts">
{
this.state.contacts.map(contact => <li key={contact.id}>
<Contact {...contact} />
</li>)
}
</ul>
<a onClick={this.loadMore}>Load More</a>
</div>
);
}
}
我只知道如何使用类的经典方法。所以更清楚的是,我基本上想要的是将这个例子转换为钩子。
要获得您想要的功能,您需要了解useState
和useEffect
。 useState
非常简单,useEffect
用于组件生命周期方法。
使用钩子的第一个经验法则是你不能将那个钩子嵌入条件中。你必须无条件地爱上钓钩。
技巧:当您使用钩子将类组件转换为功能组件时,首先要删除组件中的this
。
如果你想要代替你的代码。这是怎么回事。
import React, { useEffect, useState } from "react";
const ContactList = (props) => {
// see how it declares and set the state
const [contacts, setContacts] = useState([]);
useEffect(() => {
// for all the lifecycle methods, you can use this.
loadContacts();
// return a function for the componentWillUnmount
return;
}, [])
const loadContacts = () => {
const url = `https://student-example-api.herokuapp.com/v1/contacts.json?per=${per}&page=${page}`;
fetch(url)
.then(response => response.json())
.then(json => {
// setting state
setContacts([...contacts, json.contacts]);
});
}
return (
// whatever you want to render...
)
}
首先,你需要将基于类的组件转换为无状态组件,并且在需要深入研究useEffect()
之后,因为在这种方法中我们做副作用,它也用于研究useState()
。这使你获得成功。