【发布时间】:2019-11-13 20:18:00
【问题描述】:
我在使用动态 UI 渲染 React 时遇到问题。
我发现我的一个组件行为不端。
我有一个具有数组属性的对象,我通过 props 获得。
对象类似如下
对象:
{
title: "title",
id: 0,
rTimes: [
{ idH: 0, hours: 2 },
{ idH: 1, hours: 3 },
{ idH: 2, hours: 1 }]
};
如果我使用 console.log() 记录对象,它会显示正确的输出,但如果我在 hours 数组上使用 forEach 进行迭代,它会变得很奇怪。
this.props.Obj.rTimes.forEach((rt) => {
console.log(tr.hours);
});
=== Console Output ===
0
0
0
这阻止了我的渲染,因为它在render() 上传递了这些值,因为我正在映射这些值:
render()
{
return(
<div>
{this.props.Obj.hours.map((h) =>
<rhourComponent hours={h.hours} />
)}
</div>
);
}
所以,我最终得到了 3 个以零为值的组件。
知道为什么会发生这种情况吗?
这是一个 React SPFx 客户端 Webpart。
【问题讨论】:
-
你能用你的
rhourComponent更新问题吗?在安慰foreach回调中的值时,您将迭代器作为rt并作为tr进行安慰,是在您的代码中输入发布问题还是拼写错误? -
这是问题代码中的错字。实际代码运行良好。这很奇怪,因为如果我执行 console.log(rTimes),当我在控制台中展开对象时,它会显示数组中的 3 个对象。但如果我这样做,例如 console.log (Obj.rTimes[1].hours) 它也会显示 0。
标签: javascript reactjs typescript sharepoint-online spfx