React native set state is not working

Clash Royale CLAN TAG#URR8PPP
React native set state is not working
I am trying to update state in react native component.
But its getting errors, Could someone help me.
I'm using react-native-cli verions: 2.0.1
react-native verions: 0.55.4
Here is my code:
import React, Component from 'react'
import
Button,
Text,
View,
from 'react-native';
export class ToggleButton extends Component
state =
isDone: false
;
onAction()
const value = !this.state.isDone;
this.setState( isDone: value );
const newValue = this.state.isDone;
console.log(newValue);
render()
return (
<View>
<Button
title="Action"
onPress=this.onAction
/>
</View>
)
export default ToggleButton;
where to use, I'm a beginner to react native, could you please add that.
– Evil Coder
Aug 10 at 18:20
like this onPress= ()=> this.onAction()
– Siloé Bezerra Bispo
Aug 10 at 18:48
Thanks for that block/func solution
– Evil Coder
Aug 10 at 18:53
2 Answers
2
You have three different solutions.
The problem is that you're loosing the reference to this, because the function is not executed in the original context, so this.setState is not a function, but a undefined.
this
this.setState
In this page there are examples for all of the approaches: https://reactjs.org/docs/handling-events.html
Change
onPress=this.onAction
to
onPress=this.onAction.bind(this)
Check: this
or change
onAction() { to onAction = () => {– Pat Needham
Aug 10 at 18:29
onAction() {
onAction = () => {
thank you all, bind works for me
– Evil Coder
Aug 10 at 18:36
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
if you use a arrow function in your maybe solve the problem, you are calling a setState in another context if you pass the function like this.
– Siloé Bezerra Bispo
Aug 10 at 18:17