【发布时间】:2017-09-03 01:49:18
【问题描述】:
我正在使用 React、jQuery 和 NewsAPI。当用户更新选择的选项时,请求和状态应该改变。但是,当 Onchange 函数执行时,它会返回错误的值。函数再次执行后,该值由一个索引关闭。有人可以在不粗鲁的情况下指出我正确的方向吗:)。
import React, { Component } from 'react';
import $ from 'jquery';
import Posts from './Components/Posts';
import './style/Content.scss';
class Content extends Component {
constructor(props){
super(props);
this.state = {
posts: [],
value: 'the-verge'
}
this.change = this.change.bind(this);
}
//Ajax Request
getNews() {
$.ajax({
url: 'https://newsapi.org/v1/articles?source='+ this.state.value + '&sortBy=latest&apiKey=' + api,
dataType: 'json',
cache: true,
success: function(data) {
this.setState({ posts: [data] }, function() {
console.log(data);
})
}.bind(this),
error: function(xhr, status, err) {
console.log(err);
}
})
}
// Change the request depending on selected option
change(event){
event.preventDefault();
this.setState({value: event.target.value});
this.getNews();
}
componentWillMount(){
this.getNews();
}
componentDidMount() {
this.getNews();
}
componentWillReceiveProps(){
this.change();
}
render() {
return (
<div className="Content">
<div className="Search">
<h2>It's all in one place</h2>
<div className="Search__wrap">
<select value={this.state.value} onChange={this.change}>
<option defaultValue value="the-verge">Tech Verge</option>
<option value="techcrunch">Tech Crunch</option>
<option value="time">Time</option>
<option value="bbc-sport">BBC Sport</option>
</select>
</div>
</div>
<Posts posts={this.state.posts} />
</div>
);
}
}
export default Content;
【问题讨论】:
标签: javascript reactjs select react-native option