Member Avatar for Member #1118689

Hello, I am newbie and start learning Android mobile programming using react native.. I encounter a problem using setState state, it's keep show an error : "Can't find variable : setState"

import React, { Component } from 'react';
import {
  AppRegistry,
  StyleSheet,
  Text,
  View,
} from 'react-native';

export default class WeatherProject extends Component {
  constructor(props) {
    super (props)
    this.state={appendText:'crazy!'};
  }
  render () {
    return (
      <View> <Text onPress={() => setState({text: ' Native'})}>{this.
          props.setState +" "+ this.state.appendText}</Text> </View>
);
}
}

AppRegistry.registerComponent('WeatherProject', () => WeatherProject);

Could someone pointed where is the problem in the code?

Dani AI

Generated

The error "Can't find variable: setState" is because setState is a method on the component instance — call it as this.setState(...). The original render also references this.props.setState (which will be undefined unless a parent actually passed a setState prop) instead of reading the component state. and are correct to point out using this.setState; 's documentation reference is also relevant. 's language question is answered: this is JavaScript/React Native.

A minimal fix (inline handler) looks like this:

<Text onPress={() => this.setState({ appendText: 'Native' })}>
  {this.state.appendText}
</Text>

If you prefer not to create a new function each render, use a bound method:

handlePress = () => {
  this.setState({ appendText: 'Native' });
};
// then: <Text onPress={this.handlePress}>...</Text>

Quick troubleshooting notes: setState updates are asynchronous and may be batched — when the new value depends on the previous state use the functional form this.setState(prev => ({ count: prev.count + 1 })). Never mutate this.state directly. If this is undefined inside a handler, either bind the method in the constructor or use an arrow function so this refers to the component instance. For new projects, consider functional components with useState to avoid this entirely.

use this.setState() instead of setState().
Never use setState() directly without this.

Ex. this.setState({ text :'Native' })

use this.setState() instead of setState().

commented: This just repeats an earlier answer -3

What language do you use?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.