【发布时间】:2018-06-03 04:36:49
【问题描述】:
我正在组合一个加密货币应用程序作为实验,并从 API 中提取数据。我已经设法让所有数据都能很好地显示并每两秒搜索一次价格变化,但我想在价格变化时临时向更新的 DOM 元素添加一个类,如果下跌则为红色,如果上涨则为绿色。我目前正在从 API 中映射出每个项目,并且只希望将所需的类添加到 DOM 中的更新项目(货币)。不是所有的项目。
请看我下面的代码:
import React, { Component } from "react";
import { Link } from "react-router-dom";
import "./home.scss";
class Home extends Component {
// Create initial state and pass props
constructor(props) {
super(props);
this.state = {
isLoading: true,
coins: []
}
}
// Custom fetch data method
fetchData() {
// Fetch data
fetch('http://coincap.io/front')
// Turn response into JSON
.then(response => response.json())
// Take parsedJSON and log results
// Create individual object for each of the users
.then(parsedJSON => parsedJSON.map(coin => (
{
long: `${coin.long}`,
short: `${coin.short}`,
price: `${coin.price}`
}
)))
// Overwrite empty array with new contacts
// Set array to contacts state and set isLoading to false
.then(coins => {
this.setState({
coins,
isLoading: false
})
})
// Catch the errors
.catch(error => console.log('parsing failed', error))
}
componentDidMount() {
setInterval(() => {
this.fetchData();
console.log('refreshed');
}, 2000);
}
render() {
const { isLoading, coins } = this.state;
return (
<div className="container__wrap container__wrap--home">
<div className={`content ${isLoading ? "is-loading" : ""}`}>
<div className="panel">
{
!isLoading && coins.length > 0
? coins.map(coin => {
// Destruct each of the items in let variable
let { long, short, price } = coin;
return (
<div className="panel__item" key={short}>
<p>Name: {long}</p>
<p>Short: {short}</p>
<p>Price: ${price}</p>
<Link className="button" to={`/${short}`}>
View Coin
</Link>
</div>
);
})
: null}
</div>
<div className="loader">
<div className="loader__icon" />
</div>
</div>
</div>
);
}
}
export default Home;
简而言之,我想在每次元素更新时临时向“panel__item”添加一个类。
提前致谢!
【问题讨论】:
标签: javascript reactjs api dom