微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

javascript – 优雅的ES6方式来更新React中的状态

在React中更新状态的语法已经发生了很大变化.我正在尝试找到最简单,最优雅的方式来启动和更新它.

得到这个RN代码

const { quotes } = require('./quotes.json')

class QuoteScreen extends Component {
  state = {
    QuoteIndex: 0
  }
  render() {
    return (
      <Image ...>
        <View ...>
          ...
          <ButtonNextQuote
            onPress={() => {
              this.setState((prevstate,props) => {
                return {
                  QuoteIndex: (prevstate.QuoteIndex + 1) % (quotes.length - 1)
                }
              })
            }}
          />
        </View>
      </Image>
    )
  }
}

是否有可能减少onPress中的状态更新?

想避免两次调用匿名函数但不想引用和绑定处理程序.还想避免使用退货..

解决方法

这是我将如何做到这一点.我在setState的回调(prevstate)的第一个参数中使用了 object destructuring,出于性能原因,我使用了一个单独的函数而不是匿名函数.另外,请注意我不需要手动将函数绑定到此,因为我已经使用了箭头函数.
const { quotes } = require('./quotes.json')

class QuoteScreen extends Component {
  state = {
    QuoteIndex: 0
  }

  handleUpdateState = () => {
    this.setState(({ QuoteIndex }) => ({
      QuoteIndex: (QuoteIndex + 1) % (quotes.length - 1)
    }));
  }

  render() {
    return (
      <Image ...>
        <View ...>
          ...
          <ButtonNextQuote
            onPress={this.handleUpdateState}
          />
        </View>
      </Image>
    )
  }
}

原文地址:https://www.jb51.cc/js/155224.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐