[英]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.