首页 > 解决方案 > 在组件上调用 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;

标签: reactjsjsx

解决方案


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;

推荐阅读