Javascript 如何使用默认值在React中创建可由用户动态更新的股票行情应用程序
我正在学习通过构建一个简单的加密货币代码来做出反应:Javascript 如何使用默认值在React中创建可由用户动态更新的股票行情应用程序,javascript,reactjs,setinterval,ticker,Javascript,Reactjs,Setinterval,Ticker,我正在学习通过构建一个简单的加密货币代码来做出反应: class Ticker extends Component { constructor(props) { super(props) this.state = { currencies: [], limit: 12 } } getCurrencies = (num) => { axios.get(`
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()
this.state.limit
- 回调允许我根据更改动态更新UI(这就是我所看到的处理setState异步性的方法)
componentDidMount()
只运行一次,并且不关心状态的更新,因此用户设置的限制只是暂时的。getCurrencies函数在10秒后从componentDidMount()
调用,它显然使用了最初的初始值(12)。
我试图在handleChange()
中钩住间隔,但是只有当用户输入一个值时才会触发股票代码。
我也尝试过在render()
中进行此操作,但它似乎有问题
- 我希望我的应用程序能够呈现并不断更新正确数量的加密数据,无论用户是否更改了他想要显示的数量。如果他更改了默认值,我不希望它被他自己以外的任何东西覆盖李>
我应该使用setInterval方法开始吗?每次从状态读取,而不是仅读取一次
componentDidMount = () => {
this.getCurrencies(limit);
this.tickerTimer = setInterval(() => {
const { limit } = this.state;
this.getCurrencies(limit);
}, 10000);
}
您只需对
getCurrencies
和componentDidMount
做一点小改动:
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);
}
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);
}