![](/img/trans.png)
[英]How to access the value of an object from inside a method of the same object in Javascript?
[英]How to access object value inside static method?
我正在使用static getDerivedStateFromProps
from react 有条件地更新 state。
这是示例代码:
static getDerivedStateFromProps(nextProps, prevState) {
console.log(nextProps, prevState);
if (prevState.web_data !== nextProps) {
var data = nextProps.data;
data.sort((a, b) => new Date(b.created) - new Date(a.created));
console.log(data[0]);
// nextProps.getData({data[0].website_id});
return {
web_data: data,
// selected_web_id: data[0].website_id
}
}
else {
return null;
}
}
在上面的代码中, console.log(data[0])
返回索引 0 处的数据值,但是当我尝试访问 data[0] 中的 object 值时,它会抛出错误 website_id is undefined。
数据数组的结构是:
data = [{key:value, website_id...}, {key:value, website_id...}, {key:value, website_id...}, {key:value, website_id...}]
我建议不要使用 console.log() 来找出错误,而是尝试使用调试器并跟踪每个步骤以找出它未定义的原因。
根据我之前的说法,道具是空的,这就是为什么您无法访问 object 属性的原因。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.