【问题标题】:Add CSS class to React DOM element when updated in fetch在 fetch 中更新时将 CSS 类添加到 React DOM 元素
【发布时间】: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


    【解决方案1】:

    如果您制作了一个&lt;Coin /&gt; 组件,可能会更容易,这样您就可以跟踪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 中调用此组件并将变量作为道具传递。

    【讨论】:

    • 谢谢 Max,我创建了一个新组件并传递了 props。似乎显示正确,但不幸的是,课程保持灰色并且永远不会改变。我应该在父文件中运行 componentWillReceiveProps 吗?只是一个想法。谢谢
    • 我不确定你的意思。每次 Coin 收到新的 props 时都会自动调用 componentWillReceiveProps。它应该在 Coin 组件中定义。如果这不起作用 console.log 里面的 newProps 和 this.props。
    • 看起来参数应该是 nextProps 而不是 newProps (reactjs.org/docs/react-component.html#componentwillreceiveprops) 我已经改变了这一点,但仍然没有乐趣。控制台日志消息没有出现,这让我觉得它没有被触发。
    • 参数的名称不应该有所作为。您确定要将价格变量作为道具传递给 Coin 吗?
    • 我使用了以下内容: 我可以看到 dom 更新控制台但没有日志消息。值看起来不错。
    猜你喜欢
    • 2014-04-11
    • 1970-01-01
    • 2012-05-31
    • 2022-06-15
    • 1970-01-01
    • 2013-01-30
    • 1970-01-01
    • 2020-08-05
    • 1970-01-01
    相关资源
    最近更新 更多