Welcome to 16892 Developer Community-Open, Learning,Share
menu search
person

Categories

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>
            );
        }                           ```

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

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
https://pubads.g.doubleclick.net/gampad/ads?sz=1x1|400x300&iu=/22746323630/auto-bellow-qa-content&ciu_szs=400x300&env=vp&impl=s&gdfp_req=1&output=vast&unviewed_position_start=1&url=[referrer_url]&description_url=[description_url]&correlator=[timestamp]
Welcome to 16892 Developer Community-Open, Learning and Share
...