我是 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 次。
uj5u.com熱心網友回復:
最簡單的方法或遍歷所有物件條目是呼叫 Object.entries 然后遍歷陣列。
您遇到的問題是您需要使用 map 而不是 forEach,因為您希望將資料串列映射到 jsx 元素串列中。
const gaugeScore = Object.entries(ranges).map(([key, value]) => <div key={key}>`you've earned ${value[0]}/${value[1]} ${key} points!`</div>)
像這樣的東西應該作業。請記住,您可以將此代碼放在 jsx netween 括號中,而無需將其分配給變數。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/421965.html
標籤:
