The syntax to update state
in React has change a lot. I'm trying to find the most simple and elegant way to initiate and update it.
Got this RN code:
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>
)
}
}
Would it be possible to reduce the updating of state
in the onPress
?
Would like to avoid calling an anonymous function twice but don't want to reference and bind a handler. Would also like to avoid using the return
..
To update our state, we use this. setState() and pass in an object. This object will get merged with the current state.
To update state in React components, we'll use either the this. setState function or the updater function returned by the React. useState() Hook in class and function components, respectively.
setState method allows to change of the state of the component directly using JavaScript object where keys are the name of the state and values are the updated value of that state. Often we update the state of the component based on its previous state.
One should never update the state directly because of the following reasons: If you update it directly, calling the setState() afterward may just replace the update you made. When you directly update the state, it does not change this.
I would store the update function in a variable outside the class, e.g.
const newState = ({QuoteIndex: i}) => ({QuoteIndex: (i + 1) % nQuotes});
(of course you can chose to define the function in any way you like, maybe "terseness" isn't as important to you anymore if it isn't inlined)
And then you can just call this.setState(newState)
:
onPress={() => this.setState(newState)}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With