如何使用默认值在 React 中制作一个可以由用户动态更新的 Ticker 应用程序

How to make a Ticker App in React, using default values, that can be dynamically updated by the user

我正在学习 通过构建一个简单的加密货币代码来学习 React:

class Ticker extends Component {
    constructor(props) {
        super(props)

        this.state = {
            currencies: [],
            limit: 12
        }
    }

    getCurrencies = (num) => {
        axios.get(`https://api.coinmarketcap.com/v1/ticker/?limit=${num}`)
            .then(res => this.setState({
                currencies: res.data
            }));
    }

    componentDidMount = () => {
        const { limit } = this.state;
        this.getCurrencies(limit);
        this.tickerTimer = setInterval(() => this.getCurrencies(limit), 10000);
    }

    render() {
        const { currencies } = this.state;
        return (
        <div>
            {currencies.map((currency) => {
                return (
                    <Crypto key={currency.id} currency={currency} />
                )
            })}
        </div>
        );
    }
}

一切都运行顺利,直到我尝试实现一个输入字段以允许用户设置他自己的显示加密货币限制:

handleChange = (e) => {
    this.setState({
        limit: e.target.value
    }, () => {
        this.getCurrencies(this.state.limit);
    })
}
...
render() {
    ....
    <input onChange={this.handleChange} />
}

问题是,由于 componentDidMount() 只运行一次并且不关心状态更新,因此用户设置的限制只是临时的。 getCurrencies 函数在 10 秒后从 componentDidMount() 调用,它显然使用了超过原始值 (12) 的初始值。 我尝试挂钩 handleChange() 中的间隔,但仅当用户输入值时才会触发自动收报机。 我也尝试在 render() 中这样做,但它似乎有问题。

我错过了什么?

我在哪里可以设置间隔?

我应该使用 setInterval 方法开始吗?

每次都从状态读取,而不是一次。

componentDidMount = () => {
    this.getCurrencies(limit);
    this.tickerTimer = setInterval(() => {        
        const { limit } = this.state;
        this.getCurrencies(limit);
    }, 10000);
}

您只需要对 getCurrenciescomponentDidMount 做一点改动:

getCurrencies = () => {
    axios.get(`https://api.coinmarketcap.com/v1/ticker/?limit=${this.state.limit}`)
        .then(res => this.setState({
            currencies: res.data
        }));
},

componentDidMount = () => {
    this.getCurrencies();
    this.tickerTimer = setInterval(() => this.getCurrencies(), 10000);
}