我是 React 初学者,在循环和显示结果时遇到了困难。我试图弄清楚如何循环一个对象,其中键是字符串,值是我需要划分的数字数组。例如这里是数据在这里输入图像描述
我想打印诸如“您已获得 0/40 客户积分”之类的内容,其余内容也相同。
这是我的代码
getGaugeData = () => {
const ranges = gaugeStore.getRanges();
console.log(ranges);
// const gaugeScore = Object.entries(ranges).forEach(([key, value]) => <div>`you've earned ${value[0]}/${value[1]} ${key} points!`</div>);
// console.log('score', gaugeScore);
}
这里是调用函数 getGaugeData 的地方:
render() {
const scale = courseDataStore.getCustomData(`mti-${this.props.saveKey}`);
return (
<div className={`${this.classNamePrefix}-view ${this.props.breakpoint}`} style={{ backgroundImage: `url(${this.props.backgroundImage})` }}>
<NestedComponent component={this.props.gauges} parent={this} shouldIgnoreEmpty={false} />
<div className={`${this.classNamePrefix}-content`}>
<h2 className={`${this.classNamePrefix}-heading`} dangerouslySetInnerHTML={{ __html: this.props.heading}} />
<div className={`${this.classNamePrefix}-body`} dangerouslySetInnerHTML={{ __html: this.props.body}} />
{this.getGaugeData()}
{this.props.continueBtn && this.props.continueBtn.data && this.props.continueBtn.data.label &&
<NestedComponent component={this.props.continueBtn} parent={this} onClick={this.props.navigateNext} />
}
</div>
*{this.getGaugeData()}*
</div>
);
}
但是当我将 gaugeScore 变量记录到控制台时,我得到 undefined 而不是 div 打印 4 次。
最简单的方法或遍历所有对象条目是调用 Object.entries 然后遍历数组。
您遇到的问题是您需要使用 map 而不是 forEach,因为您希望将数据列表映射到 jsx 元素列表中。
const gaugeScore = Object.entries(ranges).map(([key, value]) => <div key={key}>`you've earn
像这样的东西您可以将此代码放在 jsx netween 括号中,而无需将其分配给变量