在 React 中更新 state
的语法发生了很大变化。我正在尝试找到最简单优雅的方式来启动和更新它。
得到这个 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
中state
的更新?
希望避免调用匿名函数两次,但又不想引用和绑定(bind)处理程序。还想避免使用 return
..
最佳答案
我会将更新函数存储在类外部的变量中,例如
const newState = ({QuoteIndex: i}) => ({QuoteIndex: (i + 1) % nQuotes});
(当然你可以选择以任何你喜欢的方式定义函数,如果它不是内联的,也许“简洁”对你来说不再那么重要了)
然后你可以调用this.setState(newState)
:
onPress={() => this.setState(newState)}
关于javascript - 在 React 中更新状态的优雅 ES6 方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44477692/