I have simple component, which takes two props: title and percent. I want dynamically show percent from 0 to whatever number is passed to component. What it does on me is increases from 0 to 1 and that is it and stop on there. Looks like it renders component, gets into componentDidMount
, increases to by 1 and then doesn't rerender component even tho setState is fired. What could be an issue?
import React from "react";
import PropTypes from "prop-types";
class ItemList extends React.Component {
constructor(props) {
super(props);
this.state = {
percent: 0
}
}
componentDidMount() {
if (this.state.percent <= this.props.number)
setTimeout(() => {
this.setState({
percent: this.state.percent + 1
})
}, 200)
}
render() {
return (
<li className="skills__programmer__content__item">
<div className="skills__programmer__content__item__name">{this.props.title}</div>
<div className="skills__programmer__content__item__percent">{ this.state.percent + "%"} </div>
</li>
)
}
}
ItemList.propTypes = {
title: PropTypes.string,
number: PropTypes.number,
}
export default ItemList;
If you want the component to continuously update to the prop passed in, you need to use setInterval
instead of setTimeout
. This way, the state will keep incrementing by 1 until it reaches the desired number. setTimeout
only executes once by design.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.