2017-04-07 1 views
1

私は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; 

答えて

0

これが正しいかどうかはわかりませんが、コードをスキミングしてわかりやすくなりました。

setStateについて重要なことは、本来ではありません。同期です。 1つの関数内に複数の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に入力する必要があります。小さなヒント:これらのAPIの1つでAPIを取得するだけで、使用するAPIを選択して別のAPIを削除する必要があります。

componentWillReceivePropsに呼び出すとエラーが発生しますイベントで渡されません。

+0

ご協力いただきありがとうございます。 'componentDidMount'で' this.state.value'を使う以外はすべて意味がありました。あなたは精緻化しますか? – Rafael

関連する問題