使用React从JSON中获取数组值

时间:2017-05-18 19:42:29

标签: json reactjs

我有一个应用程序,允许用户在Spotify API中搜索艺术家,专辑等。我能够发出请求并获得响应,但无法从显示的响应中获取值。

App.jsx

class App extends Component{
  constructor(props){
    super(props);
    this.state = {
      searchTerm: '',
      userData: []
    }
  }

  // Get data from spotify
  getUserData(){
    $.ajax({
      url: 'https://api.spotify.com/v1/search?q='+this.state.searchTerm+'&type=playlist',
      dataType: 'json',
      cache: false,
      success: function(data){
      console.log(data.playlists.items);
        this.setState({userData: data.playlists.items});
      }.bind(this),
      error: function(xhr, status, error){
      this.setState({searchTerm: null});
        alert(error);
      }.bind(this)
    });
  }
  handleFormSubmit(searchTerm){
    this.setState({searchTerm: searchTerm}, function(){
      this.getUserData();
    });
  }

  componentDidMount(){
    this.getUserData();
  }

  render(){
    return(
        <div>
          <Search onFormSubmit = {this.handleFormSubmit.bind(this)} />
          <Songs {...this.state}/>
        </div>
    )
  }
}

export default App

Songs.jsx

class Songs extends Component{

  render(){
    return(
        <div className="panel panel-default panel-order">
          <div className="panel-body">
            <div className="row">
              <div className="col-md-1"><img src={this.props.userData.images} /></div>
              <div className="col-md-11">
                <div className="row">
                  <div className="col-md-12">
                    <span><strong>Track Name: {this.props.userData.name}</strong></span>
                    <br /> Tracks:{this.props.userData.tracks}
                  </div>
                  <div className="col-md-12">
                    Type: <p>{this.props.userData.type}</p>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
    )
  }
}

export default Songs

这是示例回复的屏幕截图。 enter image description here 我应该能够从name数组中抓取urlimages等,但无法循环遍历它们。

2 个答案:

答案 0 :(得分:0)

你需要这样的东西,试试吧

    class App extends Component{
      constructor(props){
        super(props);
        this.state = {
          searchTerm: '',
          userData: []
        }
      }

      // Get data from spotify
      getUserData(){
        $.ajax({
          url: 'https://api.spotify.com/v1/search?q='+this.state.searchTerm+'&type=playlist',
          dataType: 'json',
          cache: false,
          success: function(data){
          console.log(data.playlists.items);
            this.setState({userData: data.playlists.items.map((val) => {
                name: val.name,
                href: val.href
            })});
          }.bind(this),
          error: function(xhr, status, error){
          this.setState({searchTerm: null});
            alert(error);
          }.bind(this)
        });
      }
      handleFormSubmit(searchTerm){
        this.setState({searchTerm: searchTerm}, function(){
          this.getUserData();
        });
      }

      componentDidMount(){
        this.getUserData();
      }

      render(){
        return(
            <div>
              <Search onFormSubmit = {this.handleFormSubmit.bind(this)} />
              <Songs {...this.state}/>
            </div>
        )
      }
    }

    export default App

检查ajax调用部分并根据需要对其进行操作

如果您的商品不是json格式,那么您可能需要

JSON.parse()

他们。

希望这有帮助!

答案 1 :(得分:0)

您的数据格式为:

playlist:{
  items:[
    {
      name: 'a',
      images: [
        {
          url: 'aa',
          href: 'aa'
        },
        {
          url: 'ab',
          href: 'ab'
        },
        {
          url: 'ac',
          href: 'ac'
        }
      ]
    },
    {
      name: 'b',
      images: [
        {
          url: 'ba',
          href: 'ba'
        },
        {
          url: 'bb',
          href: 'bb'
        },
        {
          url: 'bc',
          href: 'bc'
        }
      ]
    }
  ]    
}

要获取名称,首先需要迭代userData数组(它是一个对象数组)然后在里面使用图像上的另一个地图来获取网址的值。

像这样写它来访问名称和网址值:

class Songs extends Component{
  render(){
    return(
      <div>
          {this.props.userData.map(el => {
              return(
                <div key={el.name}>
                    {el.name}
                    {el.images.map(img => {
                        return <img alt='temp' src={img.url} key={img.url}/>
                    })}
                </div>
              )
          })}
      </div>
    )
  }
}

检查工作代码段:

class Songs extends React.Component{
  render(){
    return(
      <div>
          {this.props.userData.map(el => {
              return(
                <div key={el.name}>
                    {el.name}
                    {el.images.map(img => {
                        return <img alt='temp' src={img.url} key={img.url}/>
                    })}
                </div>
              )
          })}
      </div>
    )
  }
}

var playlist={
  items:[
    {
      name: 'a',
      images: [
        {
          url: 'aa',
          href: 'aa'
        },
        {
          url: 'ab',
          href: 'ab'
        },
        {
          url: 'ac',
          href: 'ac'
        }
      ]
    },
    {
      name: 'b',
      images: [
        {
          url: 'ba',
          href: 'ba'
        },
        {
          url: 'bb',
          href: 'bb'
        },
        {
          url: 'bc',
          href: 'bc'
        }
      ]
    }
  ]

}

ReactDOM.render(<Songs userData={playlist.items}/>, document.getElementById('app'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

<div id='app'/>