2017-05-18 69 views
0

我是新来的学习反应,和/阵营和本地人都遇到了以下问题。当点击<TouchableWithoutFeedback>元素时,视图不会增加。下面阵营本地增量州onPress

代码:

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> 
    ); 
    } 
} 

此外,在自主学习的兴趣,如果有,反正你会重构这个(或只需更好的做事方式),我很想听听!

回答

1

this您incrementCount函数内部不会自动绑定到类。如果将其更改为使用箭头函数,则this的范围将成为类。如果您想修改基于以前的状态值的状态,还需要使用可选功能setState:

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

谢谢,这个工作! +感谢您的良好做法建议:) – Amz

1

_incrementCount功能是错误的。

  • 您不打电话this.setState从来没有。您被分配({count: count + 1})this.setState。纠正它,删除=
  • 在表达式count + 1使用的count没有定义。将其更改为this.state.count

汇总,更改

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

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