[英]Struggling with fully changing a class component into a functional component
我正在开始学习更多关于 React 的旅程,我想尝试一个搜索音乐 API 数据库的项目。 我遇到了一些我想使用的代码,但它是用 class 组件编写的,随着该领域正在转变为功能组件,我试图将代码转换为 class 组件。 有人能帮忙吗?
import React, { Component } from 'react' import axios from 'axios' import Suggestions from 'components/Suggestions' const { API_KEY } = process.env const API_URL = 'http://api.musicgraph.com/api/v2/artist/suggest' class Search extends Component { state = { query: '', results: [] } getInfo = () => { axios.get(`${API_URL}?api_key=${API_KEY}&prefix=${this.state.query}&limit=7`).then(({ data }) => { this.setState({ results: data.data }) }) } handleInputChange = () => { this.setState({ query: this.search.value }, () => { if (this.state.query && this.state.query.length > 1) { if (this.state.query.length % 2 === 0) { this.getInfo() } } else if (.this.state.query) { } }) } render() { return ( <form> <input placeholder="Search for..." ref={input => this.search = input} onChange={this.handleInputChange} /> <Suggestions results={this.state.results} /> </form> ) } } export default Search
这是您的组件在功能组件中的转换。 我评论了我进行更改的地方:
const { API_KEY } = process.env;
const API_URL = 'http://api.musicgraph.com/api/v2/artist/suggest';
// declared as functional compoennt
const Search = () => {
// State are used through Hooks now
const [state, setState] = useState({
query: '',
results: [],
});
const getInfo = () => {
axios
.get(`${API_URL}?api_key=${API_KEY}&prefix=${state.query}&limit=7`)
.then(({ data }) => {
setState((prevState) => ({
...prevState, // Don't erase your previous state (unless it's needed)
results: data.data,
}));
});
};
const handleInputChange = () => {
setState(
(prevState) => ({
...prevstate, // Same, don't lose your previous state
query: this.search.value, // search is missing in your sample
}),
() => {
// Remove 'this' everywhere, it's useless in functional component
if (state.query && state.query.length > 1) {
if (state.query.length % 2 === 0) {
getInfo();
}
} else if (!state.query) {
}
}
);
};
// No render anymore, only return
return (
<form>
<input
placeholder='Search for...'
ref={(input) => (this.search = input)} // No idea where 'search' comes from, provide infos if you need help for this, a variable is missing i guess
onChange={() => handleInputChange()} // Arrow function to handle the 'this' context
/>
<Suggestions results={state.results} />
</form>
);
};
export default Search;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.