admin管理员组

文章数量:1277910

I'm new to learning React / React Native and have run into the following issue. When tapping on the <TouchableWithoutFeedback> element, the view does not increment.

Code below:

class SingleHabit extends Component {

  constructor() {
    super();
    this.state = {count: 0};
  }

  _incrementCount() {
    this.setState = ({
      count: count + 1
    });
  }

  render () {
    return (
      <TouchableWithoutFeedback onPress={ () => this._incrementCount() }>
        <View
          style= {[
            styles.singleHabit,
            {backgroundColor: this.props.color}
          ]}
        >
          <Text style={styles.habitNameText}>{this.props.text}</Text>
          <Text style={styles.countText}>{this.state.count}</Text>
        </View>
      </TouchableWithoutFeedback>
    );
  }
}

Also, in the interest of self-learning, if there's anyway you would refactor this (or just simply better ways of doing things), I'd love to hear!

I'm new to learning React / React Native and have run into the following issue. When tapping on the <TouchableWithoutFeedback> element, the view does not increment.

Code below:

class SingleHabit extends Component {

  constructor() {
    super();
    this.state = {count: 0};
  }

  _incrementCount() {
    this.setState = ({
      count: count + 1
    });
  }

  render () {
    return (
      <TouchableWithoutFeedback onPress={ () => this._incrementCount() }>
        <View
          style= {[
            styles.singleHabit,
            {backgroundColor: this.props.color}
          ]}
        >
          <Text style={styles.habitNameText}>{this.props.text}</Text>
          <Text style={styles.countText}>{this.state.count}</Text>
        </View>
      </TouchableWithoutFeedback>
    );
  }
}

Also, in the interest of self-learning, if there's anyway you would refactor this (or just simply better ways of doing things), I'd love to hear!

Share Improve this question asked May 18, 2017 at 22:35 AmzAmz 131 gold badge1 silver badge3 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 6

this inside your incrementCount function isn't automatically bound to the class. If you change it to use arrow functions, then the scope of this bees the class. Also its good practice to use the optional function setState if you want to modify state based offa previous state values:

   _incrementCount = () => {
     this.setState(prevState => ({ count: prevState.count + 1 }));
   }

Your _incrementCount function is wrong.

  • You are not calling this.setState never. You are assign ({count: count + 1}) to this.setState. Correct it removing the =.
  • The count used in the expression count + 1 is not defined. Change it to this.state.count.

.

Summarizing, Change

   _incrementCount() {
     this.setState = ({
       count: count + 1
     });
   }

to

  _incrementCount() {
    this.setState({
      count: this.state.count + 1
    });
  }

本文标签: javascriptReact Native Increment State onPressStack Overflow