Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.4k views
in Technique[技术] by (71.8m points)

reactjs - How to update UI with a timer in react after the render is executed

I am working on a game like this enter image description here

When the first image is dragged, i need to start the timer in seconds. When all the images are dragged, i need to stop the timer. Right now i have a timer working when an image is dragged, but the UI is not showing the current seconds. Here is some of my code, i hope you can tell me what i am doing wrong.

        constructor(props) {
            super(props);
            this.state = { name: '', sent: false, time: 0};
            const ordered = ["z","o","o","v","u"];
            ordered.sort(() => Math.random() - 0.5);
            this.images = ordered;
            this.props = props;
            this.started = false;
            this.totalSeconds = 0;
        }
        drag = (event) => {
            event.dataTransfer.setData("text", event.target.id);
            if(this.started == false) {
                this.started = true;
                setInterval(this.setTime, 1000);
            }
        }
        setTime = () => {
            ++this.totalSeconds;
            this.setState({time: this.totalSeconds});
            console.log(this.state.time);
        }
        render() {  
            let content = '';
            content = <div id="time" key={this.state.time}><img src="./img/clock.svg"/>Your score: {this.state.time} seconds </div>;
            return (
             <div>
                {content}
             </div>
            );
        }                           ```

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Try to look here: https://reactjs.org/docs/faq-state.html

this.setState({time: this.totalSeconds}) will not work, because you want set your new state with value based on previous state. Then you have to:

this.setState(state => return {...state, time: state.time + 1})

Important is also ...state spread, if you want to preserve all other state properties (keys).

Try to also look at functional React components. Is much more easier, you can define multiple state variables, that do not inherit one another. e.g.

const [time, setTime] = useState(0)

And updating the time state is as easy as: setTime(t => t+1)

Do not use time as key in component, as it is changing - you are confusing the React engine. It is still the same component, so to have correct updates, preserve the key.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...