【问题标题】:New data appears after clicking on button twice单击按钮两次后出现新数据
【发布时间】:2018-09-20 21:36:20
【问题描述】:

我正在制作一个基于天数显示图表的 react-native 应用程序

我正在调度一个 Redux Action,它在 componentDidMount 中调用 API

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供参考)

另外,如果我遗漏了任何重要的代码,请告诉我,我会在这里更新

【问题讨论】:

    标签: reactjs react-native


    【解决方案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)
    })
    

    【讨论】:

    • 对不起,我已经在我当前的代码中修复了它,但忘记在这里更新。在我的问题中更新了:)
    • 该死!是的,我忘了 setState 是异步的。这行得通,谢谢 :) 5 分钟后将其标记为已回答
    猜你喜欢
    • 2012-01-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-07-08
    相关资源
    最近更新 更多