将数组添加到父组件的状态

时间:2016-04-02 05:57:31

标签: arrays api reactjs state soundcloud

我目前正在使用Soundcloud API,我试图将返回的用户存储到数组中,然后将数组setState到父对象上。问题是当我在console.log中更新状态时,它显示它包含一个数组,但它是空的。以下是我的代码示例:



var SearchBar = React.createClass({
  getInitialState: function(){

  return {search : '',
          avatar : '',
          }

  },

  onChange: function(e){
    e.preventDefault();
    this.setState({search: e.target.value});
    console.log('does this work', this.state.search)
  
  },

  onClick: function(e){ 
    e.preventDefault();

  },

   getData: function(){
    var userAv = [];
    SC.get('/users', { q: this.state.search, limit: 10 }, function(users){
    _.each(users, function(obj){
        userAv.push(obj);
    });
   
    console.log('What is userAv', userAv);
    
  

  })
   this.setState({ avatar: userAv}, function(){
          console.log('What is this.state.avatar', this.state.avatar)
    
   });
},

  render: function(){
      return (
          <div id='search-container'>
          <input
            onChange={this.onChange}
            id='search-bar'
            type = 'text'
            value={this.state.search}
            placeholder = 'Search For Artist here'
            />
          <button
            id="search-button"
            onClick={this.getData}
            type = 'button'>
            Submit
            </button>
            <UserList />

          </div>
              )
  }
});
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:1)

您正在尝试从回调之外的异步请求中获取错误的值,在回调中移动$(".date").datetimepicker( { format: "Y", });

setState

SC.get('/users', { q: this.state.search, limit: 10 }, function(users) { this.setState({ avatar: users }); }.bind(this)); avarar getInitialState来自Array的{​​{1}}