React.js,在回调函数中设置状态

时间:2018-02-02 14:09:08

标签: javascript reactjs

我正在做反应的货币转换器。我添加了交换按钮,其任务是更改想要与他们想买的人一起销售的货币用户。所以我必须在这里完成费率时改变费率:

getRates(currencyShortcut){
    fetch('https://api.fixer.io/latest?base='+currencyShortcut)
      .then(response => response.json())
      .then(parsedJson => this.setState({currencyRates:parsedJson}))
      .catch(error => console.log('fetch error - ', error))
  }

和交换函数看起来像这样:

swapValues(e){
    e.preventDefault();
    const {currency1,currency2} = this.state;
    this.getRates(currency2.shortcut,()=>{
      this.setState({
        currency1: currency2,
        currency2:currency1
      })
    });
  }

但是尽管执行了getRates,我设置状态的回调却没有。 我看过https://github.com/spring-projects/spring-integration-samples,我想做同样的事情,但另一种方式。

3 个答案:

答案 0 :(得分:2)

您需要接受getRates中的回调参数,并在setState之后调用它。

getRates(currencyShortcut, callBack){
    fetch('https://api.fixer.io/latest?base='+currencyShortcut)
      .then(response => response.json())
      .then(parsedJson => this.setState({currencyRates:parsedJson},
          ()=>callBack()))
      .catch(error => console.log('fetch error - ', error))
  }

答案 1 :(得分:2)

你应该从getRates()调用返回它,它将获得你返回的promise,然后你可以在swapValues()函数中用.then()触发一个回调。

getRates(currencyShortcut){
    return fetch('https://api.fixer.io/latest?base='+currencyShortcut)
      .then(response => response.json())
      .then(parsedJson => this.setState({currencyRates:parsedJson}))
      .catch(error => console.log('fetch error - ', error))
  }

swapValues(e){
    e.preventDefault();
    const {currency1,currency2} = this.state;
    this.getRates(currency2.shortcut).then(()=>{
      this.setState({
        currency1: currency2,
        currency2:currency1
      })
    });
  }

这种方法应该有效。

答案 2 :(得分:1)

你用两个参数调用getRates,而函数只接受第一个。如果在getRates中接受第二个cb参数,则可以从setState({...},cb())调用它并执行回调。