Reputation: 89
i want my state
to update every 1sec but its not working.
when I console logged this second
, it works OK, but the screen is not updated
below is my codes
import React, { PureComponent } from 'react';
const date = new Date()
let seconds=date.getSeconds()
class Timer extends PureComponent {
state={
seconds:seconds,
}
changeSecond=()=>{
this.setState((prevState)=>{
this.state.seconds=prevState.seconds+1
})
}
componentDidMount(){
this.interval=setInterval(this.changeSecond,1000)
}
componentWillUnmount(){
clearInterval(this.interval)
}
render() {
return (
<>
<div>{this.state.seconds}초</div>
</>
)
}
};
Upvotes: 2
Views: 93
Reputation: 1075159
You're updating state incorrectly. The callback form of the state setter must return the new state:
changeSecond = () => {
this.setState((prevState) =>
({seconds: prevState.seconds + 1})
);
};
Live Example:
const { PureComponent } = React;
const date = new Date();
let seconds = date.getSeconds();
class Timer extends PureComponent {
state={
seconds:seconds,
};
changeSecond = () => {
this.setState((prevState) =>
({seconds: prevState.seconds + 1})
);
};
componentDidMount() {
this.interval=setInterval(this.changeSecond,1000);
}
componentWillUnmount() {
clearInterval(this.interval);
}
render() {
return (
<React.Fragment>
<div>{this.state.seconds}초</div>
</React.Fragment>
);
}
};
ReactDOM.render(<Timer />, document.getElementById("root"));
<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.13.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.13.0/umd/react-dom.production.min.js"></script>
Upvotes: 0
Reputation: 203227
Looks like an invalid state update. It should probably be:
changeSecond = () => {
this.setState((prevState)=> ({ seconds: prevState.seconds + 1 }));
}
Update from the previous state and return a new state object with the correct object shape.
Upvotes: 3