我正在整理加密货币应用程序作为实验,我从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'添加一个类。
提前致谢!
如果你制作一个<Coin />
组件可能会更容易,这样你就可以跟踪componentWillReceiveProps
的变化并管理每个硬币的状态。
尝试这样的事情:
class Coin extends React.Component {
constructor(props) {
super(props);
this.state = {
color: grey,
};
}
componentWillReceiveProps(newProps) {
if (this.props.price > newProps.price) {
this.setState({ color: 'red' });
} else if (this.props.price < newProps.price) {
this.setState({ color: 'green' });
} else {
this.setState({ color: 'grey' });
}
}
render() {
const { long, short, price } = this.props;
return (
<div className={`panel__item ${this.state.color}`} key={short}>
<p>Name: {long}</p>
<p>Short: {short}</p>
<p>Price: ${price}</p>
<Link className="button" to={`/${short}`}>
View Coin
</Link>
</div>
);
}
}
然后只需在map
中调用此组件并将变量作为props传递。