Friday 19 January 2018

javascript - this.setState React Native

itemprop="text">

I began learning React native 4 days
ago.
I'm trying to pass a property this to a
different Scene, however, I keep encountering
this error
_this.setState is not a
function
.
I believe this isn't a duplicate because I've read
through both of these Stack answers and their solutions don't seem to help me. I've got
a little bit of a different setup though so thought perhaps that might be the
issue.




href="https://stackoverflow.com/questions/31045716/react-this-setstate-is-not-a-function">React
this.setState is not a function



href="https://stackoverflow.com/questions/33381756/this-setstate-is-not-a-function">this.setState
is not a function



I know React has
changed a lot in the year since(and does so regularly) these questions were answered so
thought perhaps that might be why they didn't work for
me.



import React, { Component }
from 'react';
import { StyleSheet, Text, View, TouchableOpacity, TextInput,
Platform, } from 'react-native';
import { Actions } from
'react-native-router-flux';


const Social = () =>
{
state = {
name: ''
}
return (


onPress={() => Actions.homepage()}>
Enter your Name:




placeholder='PrimeTimeTran' onChangeText={(text) => {

this.setState({
name: text,
})
}}

value={this.state.name}
/>

onPress={() => {
alert(self.state.name)


}}
>


Next




);
}


export default
Social;


I'm following
this tutorial here(22:39) and he seems to get through my problem
with no issues. This tutorial was made November 1st, 2016 so I believe there shouldn't
be an issue with his
syntax.





the only
difference I see is that for my constructor, I'm not using a
render() with return() but instead, a
return() by itself; could this be the
issue?



Thanks in
Advance!



itemprop="text">
class="normal">Answer



Your
Social component is a stateless functional
component
(created here using the () => {} syntax); it's a pure javascript
function. Consequently setState will not be available. If you need
the component to manage its own state you'll need to create it by extending the
React.Component:



href="https://facebook.github.io/react/docs/react-component.html#setstate" rel="nofollow
noreferrer">https://facebook.github.io/react/docs/react-component.html#setstate



So,
you could declare your component as
follows:



class Social extends
React.Component {
//...implementation
here
}



You'll
then have access to setState plus other component lifecycle
methods.



(The additional note you added is also
because you're using a stateless functional component - these effectively implement the
render function, so what you can see is just the
return part of that function.)



No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...