我正在使用 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;
最佳答案
我不确定这是否正确,但这是我通过浏览代码最明显的结果。
关于setState
的一个重要的事情是它本质上不是同步的。由于一个函数中可能有多个 setState
调用,因此它们是批处理并异步执行的。因此,调用 getNews
时状态可能尚未更新。
解决方案?将值显式传递给getNews
函数。
change(event){
event.preventDefault(event.target.value);
this.setState({value: event.target.value});
this.getNews();
}
然后:
getNews(value) {
$.ajax({
url: 'https://newsapi.org/v1/articles?source='+ value + '&sortBy=latest&apiKey=' + api,
dataType: 'json',
...
这样您就不必担心 setState
的竞争条件在使用该函数之前完成。
您必须在 componentDidMount
或 componentWillMount
中使用 this.state.value
。小提示:您只需要在其中一个上获取 API,选择您要使用的一个并删除另一个,这是多余的:)
此外,在 componentWillReceiveProps
中调用 this.change
将触发错误,因为您没有传入事件。
关于javascript - Select 在初始更改时返回错误值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43282147/