gpt4 book ai didi

javascript - React/TypeScript/SPFx forEach 和复杂对象的映射函数问题

转载 作者:行者123 更新时间:2023-12-02 22:32:56 26 4
gpt4 key购买 nike

我在使用动态 UI 渲染 React 时遇到问题。

我发现我的一个组件行为异常。

我有一个带有通过 props 获取的数组属性的对象。

该对象类似于以下内容

对象:

{
title: "title",
id: 0,
rTimes: [
{ idH: 0, hours: 2 },
{ idH: 1, hours: 3 },
{ idH: 2, hours: 1 }]
};

如果我使用 console.log() 记录对象,它会显示正确的输出,但如果我在小时数组上使用 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 客户端 Web 部件。

最佳答案

rTimes 对象可能会在组件渲染后更新。

我会尝试:

  1. 通过控制台输出每个数组对象以验证 idH 是否正在更新;
  2. forEach封装在setTimeout中;
  3. 避免直接在 JSX 中使用组件属性,方法是将它们分配给内部组件变量,而不是映射该数组。

(3) 的示例:

constructor(props) {
super(props);
this.state = {
hours: this.props.Obj.hours
};
}

然后在 JSX 上:

<div>
{this.state.hours.map((h) =>
<rhourComponent hours={h} />
)}
</div>

或者(传递整个数组):

<div>
<rhourComponent hours={this.state.hours} />
</div>

然后您可以像这样操作小时:

this.setState(
update(this.state, {
hours: [], // any array you want to change to
}),
);

关于javascript - React/TypeScript/SPFx forEach 和复杂对象的映射函数问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58836488/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com