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



我正在通过构建一个简单的加密货币代码来学习 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>
);
}
}
  • getCurrencies()发出请求并填充数组this.state.currencies
  • componentDidMount()使用默认的加密货币限制 (12) 发出第一次渲染的初始请求。
  • setInterval()componentDidMount()中设置为在应用最初呈现后每 10 秒更新一次数据。

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

handleChange = (e) => {
this.setState({
limit: e.target.value
}, () => {
this.getCurrencies(this.state.limit);
})
}
...
render() {
....
<input onChange={this.handleChange} />
}
  • handleChange()将输入的值传递给this.state.limit
  • 回调允许我使用更改动态更新 UI(这就是我看到的处理 setState 的异步性所做的)。

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

  • 我希望我的应用程序呈现并不断更新适量加密货币的数据,无论用户是否更改了他想要显示的数量。如果他更改默认值,我不希望它被他自己以外的任何其他东西覆盖。

我错过了什么?

我在哪里可以设置间隔?

我应该使用 setInterval 方法以 ?

你只需要对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);
}

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

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

最新更新