reactjs - 为什么反应会跳过在组件中显示值?
问题描述
<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 个值
解决方案
每次获取都会覆盖以前的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())
}
推荐阅读
- spring-boot - 为什么我在 Processor.process() 方法中使用的“命名查询”不起作用。?- 我怎样才能修复它?
- java - 如何在 onComplete 方法中设置变量?
- python - 如何删除列表中除 1 个数字(Python)之外的所有数字?
- javascript - 传入密钥并返回对象 javascript
- google-apps-script - 使用 Google 的“应用程序脚本”在侧边栏中创建复制到剪贴板按钮
- java - SqsAckSink 使 Akka 流永远挂起,导致图形重新启动
- java - 在 Java 中复制地图对象
- swift - 为什么我的 TableView 单元格需要重用标识符?
- javascript - 如何使用 jQuery 制作图标幻灯片
- java - 格式化二维数字数组