React forEach 没有被渲染

时间:2021-04-05 16:01:42

标签: javascript reactjs foreach

如果我 console.log function arrowAnimation(){ let array = ['0.1', '0.1', '1', '0.6']; var arrowLoop = function (array) { for (let i = 0; i < arrows.length; i++) { arrows[i].style.opacity = array[i]; if (i === array.length - 1) { let lastElement = array.pop(); array = [lastElement].concat(array); arrowLoop(array); } } } arrowLoop(array); } function arrowAnimatiom() { t = setInterval(arrowAnimation, 100); } function stopArrowAnimation() { clearInterval(t); } var hover = function (d) { arrowAnimatiom(); var barElementCoords = document.getElementById(d.scaleKeys).getBoundingClientRect();; var div = document.getElementById('tooltip'); div.style.left = barElementCoords.x + 'px'; div.style.top = barElementCoords.y - 45 + 'px'; div.innerHTML = d.valuesExplanations; div.style.width = d.valuesExplanations.length + 80 + 'px' }; var hoverOut = function (d) { stopArrowAnimation(); var div = document.getElementById('tooltip'); div.style.top = -150 + 'px'; div.style.left = -150 + 'px'; } svg_.selectAll(".bar") .data(chartData_) .enter().append("rect") .attr("class", "bar__") .attr("id", function (d) { return d.scaleKeys }) .attr("x", function (d) { return x(d.scaleKeys); }) .attr("width", x.bandwidth()) .attr("y", function (d) { return y(d.scaleValues); }) .attr("height", function (d) { return height_ - y(d.scaleValues); }) .style('fill', function (d) { return setBarColor(d.scaleValues) }) .on("mouseover", hover) .on('mouseout', hoverOut) 就在 item.name 标签之前,我确实会在控制台中看到所有项目名称,但是,由于某种原因,它们没有打印在 <h1>或任何其他标签。

<h1>

请帮忙

2 个答案:

答案 0 :(得分:1)

我建议您使用 map()。这是在 React JS 中呈现数据的最佳方式 something like that

来源:https://reactjs.org/docs/lists-and-keys.html

答案 1 :(得分:1)

改用 map(),并为返回元素指定一个唯一键属性。在这种情况下,我假设它是 name,我建议使用唯一的 id 或类似的东西。

<div>
    {newArr.map((item) => 
        <h1 key={item.name}>{item.name}</h1>
     })
</div>
相关问题