简体   繁体   English

设置间隔不会更新我的 UI 上的价格(reactjs)

[英]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:我在这里有这个代码来 setInterval 以在我的反应站点上每秒更新价格:

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这是教程的屏幕截图,他的代码正在运行https://imgur.com/a/Ol1rrZf

replace代替

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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