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>
    )
  }
}

相关文章

前言 做过web项目开发的人对layer弹层组件肯定不陌生,作为l...
前言 前端表单校验是过滤无效数据、假数据、有毒数据的第一步...
前言 图片上传是web项目常见的需求,我基于之前的博客的代码...
前言 导出Excel文件这个功能,通常都是在后端实现返回前端一...
前言 众所周知,js是单线程的,从上往下,从左往右依次执行,...
前言 项目开发中,我们可能会碰到这样的需求:select标签,禁...