I am trying to increase the count value on button

2019-08-18 15:09发布

this.state = { count: 0 };

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

2条回答
劳资没心,怎么记你
2楼-- · 2019-08-18 15:31

state of a Component depend on The component's life circle. When your component unMount and reMount the state will be reset to your default value.

Thus, just store your count value outside your element. (AsyncStorage, Redux, Mobx, or just simple in your custom logic)

查看更多
贪生不怕死
3楼-- · 2019-08-18 15:41

This is the correct behaviour. If you want to persist changes after page reload, use AsyncStorage to save it.

componentDidMount() {
    let response = await AsyncStorage.getItem('count'); 
    if(response)
        this.state = { count : response};
}

componentWillUnmount() {
    AsyncStorage.setItem('count', this.state.count + '');    
}
查看更多
登录 后发表回答