简体   繁体   中英

Set Interval doesnt update price on my UI (reactjs)

I have this code here to setInterval to update the price every second on my react site:

import React, { Component } from 'react'
import './Coin.css'
import PropTypes from 'prop-types';

export default class Coin extends Component {
    constructor(props){
        super(props);
        this.state = {
            price: this.props.price 
        }
    }
    componentDidMount(){
        const callback = () => {
            //set the state to a new random value
            const randomPercentage = 0.995 + Math.random() * 0.01;
            // Dont do this:
            // this.state.price = this.state.price * randomPercentage:

            this.setState(function(oldState){
                return {
                    price: oldState.price * randomPercentage
                };
            });
        }
        setInterval(callback, 1000);  
    }
    render() {
        return (
            <tr className="coin-row">
                <td>{this.props.name}</td>
                <td>{this.props.ticker}</td>
                <td>${this.props.price}</td>
            </tr>
        );
    }
}

Coin.propTypes = {
    name:PropTypes.string.isRequired,
    ticker: PropTypes.string.isRequired,
    price: PropTypes.number.isRequired
}

When i run this app the price on my site should update every second with some random Number

This is a screenshot of my UI在此处输入图像描述

When i run it nothing happens- price isnt changing every second and i also get no errors in my console. The only thing that i see is this entry in the console:

[HMR] Waiting for update signal from WDS...

Whats wrong here? And how can i fix it?

Here is a screenshot from the tutorial and his code is working https://imgur.com/a/Ol1rrZf

replace

<td>${this.props.price}</td> with <td>${this.state.price}</td>

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM