首页 > 解决方案 > 为什么反应会跳过在组件中显示值?

问题描述

    <div className = 'card'> 
      <p>{props.rate.code} {props.rate.currency}</p>
      <p>{props.rate.mid}
      {console.log(props.code)}</p>
    </div>
)

在 console.log 我可以看到所有代码,但在网站上只显示随机的几个,如果我刷新它会改变。我真的不知道,这是教程中的代码,但我在另一个数据集上工作。我有数据方式的二维表我获取数据

  componentDidMount() {
    fetch('http://api.nbp.pl/api/exchangerates/tables/A/?format=json')
      .then((response) => response.json())
      .then(values =>this.setState({currency: values}))
    fetch('http://api.nbp.pl/api/exchangerates/tables/B/?format=json')
      .then((response) => response.json())
      .then(values =>this.setState({currency: values}))
    fetch('http://api.nbp.pl/api/exchangerates/tables/C/?format=json')
      .then((response) => response.json())
      .then(values =>this.setState({currency: values}))
  }

使用地图

    {props.currency.map(
          (table,index) =>
            table.rates.map(rate =>(
              <Card key={index+rate.code} rate={rate}/>
            )
          )
        )}

在应用程序组件中

<CardList currency={this.state.currency}/>

在控制台中我可能看到 200 个值,但在现场我随机看到 10-100 个值

标签: reactjs

解决方案


每次获取都会覆盖以前的currency状态,这样您就会丢失以前的数据。为避免您需要在添加新状态时复制当前状态:

  componentDidMount() {
    fetch('http://api.nbp.pl/api/exchangerates/tables/A/?format=json')
      .then((response) => response.json())
      .then(values =>this.setState(({ currency }) => {currency: [...currency, ...values]}))
    fetch('http://api.nbp.pl/api/exchangerates/tables/B/?format=json')
      .then((response) => response.json())
      .then(values =>this.setState(({ currency }) => {currency: [...currency, ...values]}))
    fetch('http://api.nbp.pl/api/exchangerates/tables/C/?format=json')
      .then((response) => response.json())
      .then(values =>this.setState(({ currency }) => {currency: [...currency, ...values]}))
  }

虽然这看起来有点脏,因为您正在执行多个状态更新。您可以等待每个响应,然后更新您的状态:

  async componentDidMount() {
    try {
      const currencyA = await this.getCurrencyFromTable('A');
      const currencyB = await this.getCurrencyFromTable('B');
      const currencyC = await this.getCurrencyFromTable('C');
      const currency = [...currencyA, ...currencyB, ...currencyC];

      this.setState({ currency })
    } catch (error) {
      console.log(error)
    }
  }

  getCurrencyFromTable(table) {
    return fetch(`http://api.nbp.pl/api/exchangerates/tables/${table}/?format=json`)
    .then((response) => response.json())
  }

推荐阅读