将数组添加到父组件的状态
Adding an array to state of parent component
我目前正在使用 Soundcloud API,我正在尝试将返回的用户存储到一个数组中,然后将该数组设置为父对象。问题是当我 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>
)
}
});
您正在尝试从回调之外的异步请求中获取值,这是错误的,请将 setState
移入回调
SC.get('/users', { q: this.state.search, limit: 10 }, function(users) {
this.setState({ avatar: users });
}.bind(this));
还将 getInitialState
中的 avarar
从 String
更改为 Array
我目前正在使用 Soundcloud API,我正在尝试将返回的用户存储到一个数组中,然后将该数组设置为父对象。问题是当我 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>
)
}
});
您正在尝试从回调之外的异步请求中获取值,这是错误的,请将 setState
移入回调
SC.get('/users', { q: this.state.search, limit: 10 }, function(users) {
this.setState({ avatar: users });
}.bind(this));
还将 getInitialState
中的 avarar
从 String
Array