使用输入框从React.js中提取GET请求的结果

时间:2018-03-20 18:47:01

标签: reactjs get axios

我有一个组件,我希望能够使用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(artist) {
  this.setState(function() {
      return {
        artists: null
        artistSearched: handleSearchTermChange(artist),
      };
    });

    api.getItunesArtists(artist).then(
      function(artists) {
        this.setState(function() {
          return {
            artists: artists,
          };
        });
      }.bind(this)
    );
  }

任何帮助将不胜感激!

1 个答案:

答案 0 :(得分:0)

 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只是您需要将此对象的属性替换为您对每位艺术家的请求返回的属性的名称。