2

下面是我的 React 组件,谁能理解为什么 react.Fragment 在 getResults 函数中根本不渲染?

我希望它最终显示来自 api 响应的结果。

我的 api 查询工作正常,我可以得到我想要的数据,但我很难在组件中显示它。

import React from "react";
import axios from "axios";
import SearchInput, {
  createFilter
} from "react-search-input";
import {
  spotifySearchURL
} from "../../constants";

export class SearchPanel extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
      searchValue: "",
      tracks: {},
      selectedOption: null
    };
    this.handleSearch = this.handleSearch.bind(this);
  }

  getSearchValue(value, token) {
    this.setState({
      searchValue: value
    });
    this.handleSearch(value, token);
    console.log(value);
  }

  getResults() {
    let tracks = this.state.tracks;
    let track;
    Object.keys(tracks).map(function(key, items) {
      track = tracks[key];
      console.log(track, track.name);
      return ( 
       <React.Fragment >
        <h1 > {track.name} < /h1>
       </React.Fragment>
      );
    });
  }

  handleSearch = (value, token) => {
    const encoded = encodeURIComponent(value);
    let url = `${spotifySearchURL}${encoded}&type=track`;
    console.log(url);

    const params = {
      headers: {
        Authorization: " Bearer " + token,
        accept: "application/json",
        "Content-Type": "application/x-www-form-urlencoded"
      },
      data: null
    };

    axios
      .get(url, params)
      .then(response => {
        this.setState({
          tracks: response.data.tracks.items
        });

        console.log(response.data.tracks.items);
      })

      .catch(error => {
        console.log(error);
      });
  };

  render() {
    return ( 
     <div className ="search-panel">
      <SearchInput
       className = "search-input"
       value = {
         this.state.searchValue
       }
       onChange = {
         value => this.getSearchValue(value, this.props.token)
       }
      />

      {this.getResults()}
     </div>
    );
  }
}

export default SearchPanel;
4

1 回答 1

1

您必须返回从mapfrom返回的数组getResults

getResults() {
  let { tracks } = this.state;
  let track;

  return Object.keys(tracks).map(function(key, items) {
    track = tracks[key];

    return ( 
      <React.Fragment>
        <h1> {track.name} </h1>
      </React.Fragment>
    );
  });
}
于 2018-08-04T15:40:27.537 回答