【问题标题】:React native not re-rendering after setState在 setState 之后反应原生不重新渲染
【发布时间】:2020-05-06 20:29:55
【问题描述】:

我不明白为什么组件在 setState 之后没有被重新渲染。我认为绑定 onPress 方法会有所帮助,但没有。 当我点击 TouchableHighlight 时,它会改变 View backgroundColor,但如果我再次点击它就不会再改变了。

class Item extends Component{

  state={
    currentColor:"#FFFFF"
  }

  onClick() {
    console.log(this.state.currentColor)
    if (this.state.currentColor=='#FFFFF'){
      color='green'
    } else {
      color='#FFFFF'
    }
    this.setState({currentColor:color})
  }

  render(){
    return (
      <TouchableHighlight onPress={ this.onClick.bind(this) } >
        <View style={[styles.item, {backgroundColor: this.state.currentColor}]}>
          <Text style={styles.title}>{this.props.title}</Text>
        </View>
      </TouchableHighlight>
    );
  }
}

【问题讨论】:

  • #FFFFF 不是有效的颜色代码,请尝试#FFFFFF
  • 不确定是否相关,但color 未在您的函数范围内定义。

标签: javascript reactjs react-native


【解决方案1】:

问题似乎在于您如何在函数中设置currentColor。像你一样做这件事并不能证明你会为你得到正确的currentColorsetStateReact's documentation 建议使用提供给setStatestate 参数:

// no need to bing if you use an arrow function here

onClick = () => {
  console.log(this.state.currentColor);
  this.setState(state => ({
    currentColor: state.currentColor === '#FFF' ? 'red' : '#FFF',
  }));
};

【讨论】:

    猜你喜欢
    • 2018-07-17
    • 2019-12-13
    • 1970-01-01
    • 2019-08-09
    • 2016-10-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多