单击两次按钮后出现新数据

时间:2018-09-20 21:36:20

标签: reactjs react-native

我正在制作一个基于本机的应用程序,该应用程序显示基于天数的图表

我正在调度Redux动作,该动作在API中进行了componentDidMount调用

componentDidMount() {
    this.props.coinHistory(this.state.days, this.props.navigation.state.params.coinShortName) 
    this.props.coinComplete(this.props.navigation.state.params.coinShortName)
}

最初我的状态是

state = {
    days: 1
}

现在,我有一个按钮可以更改上述状态

  <Button
      onPress={() => this.changeHistoryChart(7)}
      title="Learn More"
      color="#841584"
     accessibilityLabel="Learn more about this purple button" />

changeHistoryChart看起来像这样

   changeHistoryChart = (value) => {
        this.setState({days: value})
this.props.coinHistory(this.state.days, this.props.navigation.state.params.coinShortName) 
    }

[问题:] ,尽管如此,但问题是我需要单击两次按钮以显示新数据,或者单击另一个按钮以显示上一个按钮的数据。我可能在做错什么,该如何解决? (下面附有GIF供参考)

如果万一我错过了任何重要的代码,请告诉我,我将在这里进行更新

enter image description here

1 个答案:

答案 0 :(得分:1)

您正在立即调用onPress处理程序:

onPress={this.changeHistoryChart(7)}

您应该在此处使用回调函数,例如:

onPress={() => this.changeHistoryChart(7)}

此外,setState是异步的,因此如果您依赖更新状态进行其他操作,则需要回调。

this.setState({days: value}, () => {
    this.props.coinHistory(this.state.days, this.props.navigation.state.params.coinShortName)
})
相关问题