Issue
I am trying to make a component "blink" on my page. I was thinking about setting a visible: true state in my componentWillMount method and then put a timeout of 1s in componentDidUpdate to set state to the "opposite" of the previous state. As I see it the component lifecycle looks like this :
sets state to visible to true (componentWillMount that runs only once and is not triggering a rerender) enters componentdidUpdate waits 1s hides component (setstate to visible false) enters componentDidUpdate waits 1s shows component (setstate to visible true)
However my component is blinking but the intervals of hide and show are not regular, they change and dont seem to follow the 1s logic
Here's my component code :
class ResumeChronoButton extends Component {
componentWillMount() {
console.log('in componentWillMount')
this.setState({ visible: true })
}
componentDidUpdate() {
console.log('in componentDidUpdate')
setTimeout(() => this.setState({ visible: !this.state.visible }), 1000)
}
// componentWillUnmount(){
// clearInterval(this.interval)
// }
render() {
const { textStyle } = styles;
if (this.state.visible) {
return (
<TouchableOpacity onPress={this.props.onPress}>
<Pause style={{ height: 50, width: 50 }} />
</TouchableOpacity>
);
}
else {
return (
<View style={{ height: 50, width: 50 }}>
</View>
)
}
}
};
How can I make my component blink at regular time interval.
Solution
The following works for me
componentDidMount = () => {
this.interval = setInterval(() => {
this.setState((state, props) => {
return {
visible: !state.visible,
};
});
}, 1000);
};
componentWillUnmount = () => {
clearInterval(this.interval);
};
and then your render can just check this.state.visible
to determine if it needs to show or not.
alternatively you could change the setState
to
this.setState({visible: !this.state.visible})
Answered By - Johan
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.