2017-05-21 59 views
0

使用保存特定加密貨幣硬幣的對象數組的api端點。在反應中清除值狀態

我創建了一個表單,用戶可以輸入特定的硬幣並點擊提交,它會返回價格。然後該硬幣將檢查它是否在api中的一個對象數組中。如果它是有效的,那麼我將它推入構造函數中的過濾結果數組中。

我的第一個搜索查詢有效,但當我執行第二次查詢搜索並點擊提交按鈕時,它失敗並重新加載頁面。

constructor() { 
    super(); 
    this.state = {value: ''}; 
    this.state = {coin: []}; 
    this.state = {items: []}; 
    this.state = {filteredResults: []}; 

    this.handleChange = this.handleChange.bind(this); 
    this.handleSubmit = this.handleSubmit.bind(this); 
    } 

    handleChange(event) { 
    this.setState({value: event.target.value}); 
    } 

    handleSubmit(event) { 
    let coin = this.state.value; 
    this.findCoin(coin); 
    event.preventDefault(); 
    } 

    findCoin(id) { 
    this.state.items.forEach(function(currency){ 
     if(currency.id === id) { 
     this.state.filteredResults.push(currency) 
     } 
    }, this); 

    this.setState({filteredResults: this.state.filteredResults[0]}); 
    } 

    componentDidMount() { 
    fetch(`https://api.coinmarketcap.com/v1/ticker/`) 
     .then((result)=> { 
     result.json() 
     .then(json => { 
     this.setState({items: json}) 
     }); 
    }); 
    } 

    render() { 
    return (
     <div className="App"> 
     <form onSubmit={this.handleSubmit}> 
      <label> 
      Name: 
      <input type="text" value={this.state.value} onChange={this.handleChange} /> 
      </label> 
      <input type="submit" value="Submit" /> 
     </form> 
     <div> Price: $ {this.state.filteredResults.price_usd} 
     </div> 
     </div> 
    ); 
    } 
} 
+0

也許不要緊,你的問題,但國家在構造函數的設定可能要看起來像這樣:'this.state = {值:「」,硬幣:[],項目:[] ,filteredResults:[]}' –

回答

0

在這種方法的問題:

findCoin(id) { 
 
    this.state.items.forEach(function(currency){ 
 
     if(currency.id === id) { 
 
      this.state.filteredResults.push(currency) 
 
     } 
 
    }, this); 
 

 
    this.setState({filteredResults: this.state.filteredResults[0]}); 
 
}

在線路

this.setState({filteredResults: this.state.filteredResults[0]}); 

要設置filteredResults(這是一個數組)的一個對象和上第二次搜索行

this.state.filteredResults.push(currency) 

給你一個錯誤,因爲filredResults是一個字符串沒有push方法。

並且由於handleSubmit方法的最後一行上有event.preventDefault,它不會執行,因爲前面的錯誤和表單正在提交。

+0

在第二次搜索時,當我把一個調試器語句,它看起來像它仍然是一個對象? –

+0

編輯它。是的,它是貨幣對象,但不是數組,因爲它是預期的 – lunochkin

0

該方法是變異的狀態,它規避了React的狀態檢查;

findCoin(id) { 
    this.state.items.forEach(function(currency){ 
     if(currency.id === id) { 
     this.state.filteredResults.push(currency) 
     } 
    }, this); 

    this.setState({filteredResults: this.state.filteredResults[0]}); 
    } 

使用的方法,例如過濾器,給出一個新的數組引用:

const filtered = this.state.items.filter(ccy=> ccy.id === id); 
this.setState({filteredResults: filtered[0]}; 

另外,作爲其他海報中的一個已經提到的,聲明filterResults作爲對象(如果只有永遠將顯示一個過濾結果),因爲它從數組變爲對象。

this.state = {filteredResults: {}}; 
+0

這不是唯一的問題,數據類型也是從數組到數據類型的變化 – lunochkin