我正在使用map循环通过数组,然后用它填充div,但它总是空的:
这是我的一些代码:
const [scoreOptions, setScoreOptions] = useState(initialScoreOption);
const initialScoreOption = [
{ id: 1, selected: false, icon: 'far fa-smile', label: 'lala'},
{ id: 2, selected: false, icon: 'far fa-meh', label: 'lalala'},
{ id: 3, selected: false, icon: 'far fa-frown', label: 'lalala'}
];
let iconosTexto;
if (scoreOptions){
iconosTexto = scoreOptions.map(icono => {
return(
<div className="contenedorIconoTexto">
<div className="iconoElemento">
<i className={blue ? `blueIcon ${icono.icon}` : `greyIcon ${icono.icon}`}>
</i>
</div>
<div className="iconoTexto">
{icono.label}
</div>
</div>
)
});
}
然后我在渲染上有了这个
<div className="container">
{ iconosTexto }
</div>
带有类容器的div 在应该填充上述所有内容时为空 谁能帮我解决这个问题?
首先,在useState(initialScoreOption)
之前声明initialScoreOption
。
在 map 中渲染元素时使用 setkey
prop:
iconosTexto = scoreOptions.map((icono) => {
return (
<div key={icono.id} className="contenedorIconoTexto">
...
然后确保iconosTexto
始终具有价值。
试试这个方式:
const IconosTexto = () => scoreOptions.map(icono => {
return (
<div className="contenedorIconoTexto">
<div className="iconoElemento">
<i className={blue ? `blueIcon ${icono.icon}` : `greyIcon ${icono.icon}`}
>
</i>
</div>
<div className="iconoTexto">{icono.label}</div>
</div>
)
}
render (
<div className="container">
<IconosTexto />
</div>
)
您需要在将initialScoreOption
传递给useState
之前声明它:
const initialScoreOption = [
{ id: 1, selected: false, icon: 'far fa-smile', label: 'lala'},
{ id: 2, selected: false, icon: 'far fa-meh', label: 'lalala'},
{ id: 3, selected: false, icon: 'far fa-frown', label: 'lalala'}
];
const [scoreOptions, setScoreOptions] = useState(initialScoreOption);
演示