reactjs - 在组件上调用 Map 时未渲染的项目
问题描述
我很难弄清楚为什么,当我为我的交换组件调用 map 函数时,我的交换信息组件中没有显示任何内容。以下是我的组件的定义。
我想我错过了一些简单的东西,但我似乎无法弄清楚。我还是新手,React
并且总是在渲染一组组件时遇到问题。这样做时我可以遵循的任何最佳实践?
家庭组件
class HomePage extends React.Component {
//some setup here
componentDidMount() {
//some action here
}
componentWillReceiveProps(newProps) {
//some prop checking here
}
render() {
return (
<div>
<div className="row flex-container">
{
<ExchangeInformation
coin={this.state.coin}
exchangeRates={this.state.exchangeRates}
/>
}
</div>
</div>
);
}
}
function mapStateToProps(state, ownProps) {
return {
//returning state selectors here
};
}
function mapDispatchToProps(dispatch) {
return {
//return actions here
};
}
HomePage.propTypes = {
ccActions: PropTypes.object.isRequired
};
export default connect(mapStateToProps, mapDispatchToProps)(HomePage);
交换信息组件:
const ExchangeInformation = ( {coin, exchangeRates} ) => {
return (
<div className="exchange-rate">
<h3>Current Exchange Rates</h3>
{
Object.keys(exchangeRates).map(function(key, index) {
<div>
<ExchangeRate
coin={coin}
exchangeRate={exchangeRates[key]}
symbol={key}
key={index}
/>
</div>
})
}
</div>
);
};
ExchangeInformation.propTypes = {
coin: PropTypes.object.isRequired,
exchangeRates: PropTypes.object
}
export default ExchangeInformation;
汇率组件:
const ExchangeRate = ( {coin, exchangeRate, symbol} ) => {
return (
<label className="label-field">
<strong>{"1 " + coin.CoinName}</strong> is equal to <strong>{exchangeRate + " (" + symbol + ")"}</strong>
</label>
);
};
ExchangeRate.propTypes = {
coin: PropTypes.object.isRequired,
exchangeRate: PropTypes.number,
symbol: PropTypes.string
}
export default ExchangeRate;
解决方案
在Exchange Information Component
中,您需要return
在 map 函数中使用语句。
const ExchangeInformation = ( {coin, exchangeRates} ) => {
return (
<div className="exchange-rate">
<h3>Current Exchange Rates</h3>
{
Object.keys(exchangeRates).map(function(key, index) {
// add return statement here
return (<div>
<ExchangeRate
coin={coin}
exchangeRate={exchangeRates[key]}
symbol={key}
key={index}
/>
</div>)
})
}
</div>
);
};
ExchangeInformation.propTypes = {
coin: PropTypes.object.isRequired,
exchangeRates: PropTypes.object
}
export default ExchangeInformation;
推荐阅读
- git - 我没有从master分支出来,而是从一个分支分支出来
- twilio - 呼叫转移+短信+耳语?
- vue.js - 页面重新加载导致 Vuex getter 返回 undefined
- angular - 为什么添加 HTTP 拦截器会导致 CORS 错误?
- r - 将 cellosaurus.xml 文件转换为 R 中的 data.frame
- asp.net-mvc - ASP .NET MVC 查询计数问题
- spring-boot - Spring Boot + Cloud URL 重写实现
- mongodb - Nifi PutMongo - 如何使用流文件的属性值而不是流文件内容将文档插入 MongoDB?
- angular - 在 Angular 6 中使用 trackBy 和 ngFor 可以提高性能?
- c++ - OpenGL LookAt 矩阵基础