2017-05-21 140 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