gpt4 book ai didi

javascript - react : Not able to access the value of state variable and each child in an array or iterator should have a unique "key" prop

转载 作者:行者123 更新时间:2023-12-02 13:58:55 24 4
gpt4 key购买 nike

我收到一个错误:数组或迭代器中的每个子项都应该有一个唯一的“key” Prop ,如果我在图表提供程序组件中执行 console.log(sTime) 。它显示 NaN。我必须在 ChartComponent 中传递这个值。

此图表提供程序组件。

var React = require('React');
var ReactDOM = require('ReactDOM');
var Chart = require('react-google-charts').Chart;
vat ChartComponent = require('ChartComponent');
var ChartConfig = require('ChartConfig');
var date = new Date();

var LineChart = React.createClass({
getInitialState: function()
{
return ({
eTime: date.getTime(),
sTime: this.eTime - (60 * 1000 * range),
});
},
onUpdate: function(){
var _this = this;
date = new Date();
_this.setState({
eTime: date.getTime(),
sTime: this.eTime - (60 * 1000 * range)
})

},
render: function () {
var _this = this;
var item = [];

ChartConfig.cList.forEach(function(col, cindex) {
col.wList.forEach(function(widget, windex) {
console.log(_this.state.sTime);
item.push ( <div>
<div key={"title_" + cindex + windex} >
<div> widget.title </div>
</div>
<div key={"chart" + cindex + windex} >
<ChartComponent width="500px" height="400px"
sTime={_this.state.sTime}
eTime={_this.state.eTime} >
</div>
</div>
);
});
});

return (
<div >
{item}
</div>
)
}
});
module.exports = LineChart;

ChartConfig.js 文件包含数据:

module.exports = {
cList : [ {
widgetList : [ {
title : "Average(Kbps)",
}, {
title : "Average DL(Kbps)",
}, {
title : "DL",

} ],
index : 0,
}, {
widgetList : [ {
title : "Minutes",
}, {
title : "Cell",
}, {
title : "UL",
} ],
index : 1,
} ],
};

最佳答案

问题似乎出在这里:

getInitialState: function() {
return ({
eTime: date.getTime(),
sTime: this.eTime - (60 * 1000 * range),
});
},

更改为:

getInitialState: function() {
return ({
eTime: date.getTime(),
sTime: date.getTime() - (60 * 1000 * range),
});
},

看起来您正在尝试在几个地方使用 this.eTime 但它不是直接在组件对象上的属性,而是组件状态对象的一部分。确保您始终使用 this.state.eTime ,除非您最终确实执行了 this.eTime = Something ,如果它的值将要更改,则它应该是国家的一部分。

至于键错误,需要向 forEach 循环中生成的组件添加一个键值,如下所示:

col.wList.forEach(function(widget, windex) {
console.log(_this.state.sTime);
item.push ( <div key={windex}> // add unique key so react can check diff for performance
<div key={"title_" + cindex + windex} >
<div> widget.title </div>
</div>
<div key={"chart" + cindex + windex} >
<ChartComponent width="500px" height="400px"
sTime={_this.state.sTime}
eTime={_this.state.eTime} >
</div>
</div>
);
});
});

参见https://facebook.github.io/react/docs/lists-and-keys.html

但基础知识是,当您使用迭代器生成 JSX 时,您应该添加一个唯一的键,这样当 React 重新渲染组件时,它将检查是否有基于该键的任何更改。否则,当 React 重新渲染时,没有唯一的键,React 会假设它只需要重新渲染整个性能较低的东西。

关于javascript - react : Not able to access the value of state variable and each child in an array or iterator should have a unique "key" prop,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40516645/

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