Reputation: 2157
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.
React 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 (
<View style={ styles.container }>
<Text style={ styles.Name } onPress={() => Actions.homepage()}>
Enter your Name:
</Text>
<TextInput style={ styles.TextInput} placeholder='PrimeTimeTran' onChangeText={(text) => {
this.setState({
name: text,
})
}}
value={this.state.name}
/>
<TouchableOpacity
onPress={() => {
alert(self.state.name)
}}
>
<Text style={ styles.buttonText }>
Next
</Text>
</TouchableOpacity>
</View>
);
}
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!
Upvotes: 1
Views: 1456
Reputation: 2308
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:
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.)
Upvotes: 4