私はReact、jQuery、およびNewsAPIを使用しています。ユーザーが選択したオプションを更新すると、要求と状態が変更されます。ただし、Onchange関数を実行すると、間違った値が返されます。関数が再度実行されると、値は1つのインデックスだけオフになります。誰かが失礼なことなしに正しい方向に私を向けることができます:)。Selectが最初の変更で間違った値を返す
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;
ご協力いただきありがとうございます。 'componentDidMount'で' this.state.value'を使う以外はすべて意味がありました。あなたは精緻化しますか? – Rafael