我有一个组件,我希望能够使用GET
向itunes提取axios
请求的结果。
import React, { Component } from 'react';
import api from '../utils/api';
import axios from 'axios';
export default class App extends Component {
constructor(props) {
super(props);
this.state = { artists: [], artistSearched: '' };
this.handleSearchTermChange = this.handleSearchTermChange.bind(this);
this.getArtists = this.getArtists.bind(this);
}
componentDidMount() {
this.getArtists(this.state.artists);
}
getArtists(artist) {
this.setState(function() {
return {
artists: artist,
};
});
api.getItunesArtists(artist).then(
function(artists) {
this.setState(function() {
return {
artists: artists,
};
});
}.bind(this)
);
}
handleSearchTermChange(event) {
this.setState({ artistSearched: event.target.value });
}
render() {
return (
<div>
<h1>Itunes Album Fetcher</h1>
<form style={{ marginTop: '20px' }}>
<input
onChange={this.getArtists}
value={this.state.searchTerm}
className="form-control"
placeholder="Enter album name"
/>
</form>
</div>
);
}
}
我想我必须重写'getArtists'方法。但那没用。
getArtists(artist) {
this.setState(function() {
return {
artists: null
artistSearched: handleSearchTermChange(artist),
};
});
api.getItunesArtists(artist).then(
function(artists) {
this.setState(function() {
return {
artists: artists,
};
});
}.bind(this)
);
}
任何帮助,将不胜感激!
render() {
{artists, artistSearched} = this.state;
const filteredArtists = artists.length && artists.filter(item => item.artistName.toLowerCase().includes(artistSearched.toLowerCase()))
return (
<div>
<h1>Itunes Album Fetcher</h1>
<form style={{ marginTop: '20px' }}>
<input
onChange={this.getArtists}
value={this.state.searchTerm}
className="form-control"
placeholder="Enter album name"
/>
</form>
{filteredArtists.length ? <div> filteredArtists.map(item => item.artistName) </div> : <div> no artists searched </div>}
</div>
);
}
您从未使用搜索词过滤艺术家数组。如果其他一切正常,那么过滤艺术家将保留与您的搜索词包含相同名称的艺术家。
const filteredArtists = artists.length && artists.filter(item => item.artistName.toLowerCase().includes(artistSearched.toLowerCase()))
item.artistName只是您需要将对象的属性替换为您对每个艺术家的请求返回的属性的名称。