【问题标题】:React Js If Else using data from APIReact Js If Else 使用来自 API 的数据
【发布时间】:2018-10-05 08:35:58
【问题描述】:

此 data.quotes.USD.percent_change_1h 是从 API 获取数据,我需要它来检查它是否包含“-”(减号)。如果它包含减号,则来自 API 的数据编号颜色为红色,否则为绿色。但不知何故,我的代码不起作用

class Cointable extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      error: null,
      isLoaded: false,
      data: [],
    }
  }

  componentDidMount() {
    this.timer = setInterval(
      () =>
        fetch(conf[this.props.coin].url)
          .then(res => res.json())
          .then(
            result => {
              this.setState({
                isLoaded: true,
                data: result.data,
              })
            },
            error => {
              this.setState({
                isLoaded: true,
                error,
              })
            }
          ),
      5000
    )
  }
render(){
const { error, isLoaded, data } = this.state
    if (error) {
      return <div>Error: {error.message}</div>
    } else if (!isLoaded) {
      return <div>Loading...</div>
    }
return(

//这是主要问题所在

  {data.quotes.USD.percent_change_1h.includes('-') === true ? (
    <TD style={{ color: 'red' }}>{data.quotes.USD.percent_change_1h}</TD>
                  ) : (
    <TD style={{ color: 'green' }}>{data.quotes.USD.percent_change_1h}</TD>
                  )}
)
}

它让我的桌子都消失了,不会显示任何东西。 percent_change_1h 的值类似于“0.7”或“-0.7”

【问题讨论】:

  • 您能添加更多代码或上下文吗?
  • “不起作用”不是一个很有帮助的描述。发生什么了?是否有任何错误信息?提供minimal reproducible examplepercent_change_1h 有什么价值?
  • 它让我的桌子都消失了,不会显示任何东西。 percent_change_1h 的值类似于“0.7”或“-0.7”

标签: javascript reactjs api ecmascript-6 jsx


【解决方案1】:

你可以这样检查:

data.quotes.USD.percent_change_1h.indexOf('-') > -1

【讨论】:

    【解决方案2】:

    您的数据在构造函数中被初始化为数组。是否正确?顺便提一句。默认情况下包括返回布尔值。在三元运算符中检查值 true 是多余的。顺便说一句,它看起来很正确,所以我想你的数据有问题吗?

    【讨论】:

    • 是的。如果我没有检查它,数据返回就好了。我只需要它按值改变颜色。
    【解决方案3】:

    检查这两件事..

    1. data.quotes.USD.percent_change_1h 的类型必须是字符串
    2. 大部分IE版本不支持includes(),所以如果你在IE中做的话,请检查你在其他浏览器中的代码

    【讨论】:

    • 我试过用 data.quotes.USD.percent_change_1h.toString().indexOf('-') 还是不行
    【解决方案4】:

    你打开控制台了吗? 您可能有一个错误,因为您正在获取数据,然后在设置之前尝试使用它。 此外,您将数据初始化为数组,然后将其用作对象。如果 data 是一个对象数组,我建议你创建一个辅助渲染方法并使用map() 方法。

    类似这样的:

    renderData = () => {
        return this.state.data.map(item => { 
            return (
            item.quotes.USD.percent_change_1h.includes('-')
                ? <TD style={{ color: 'red' }}>{item.quotes.USD.percent_change_1h}</TD>
                : <TD style={{ color: 'green' }}>{item.quotes.USD.percent_change_1h}</TD>
            )
        })
    }
    

    然后在你的主 render() 方法中像这样调用它 {this.renderData()}.

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-04-08
      • 2016-03-16
      • 1970-01-01
      • 1970-01-01
      • 2019-10-08
      • 2022-11-17
      • 2022-01-21
      • 2018-08-01
      相关资源
      最近更新 更多