简体   繁体   English

如何在 static 方法中访问 object 值?

[英]How to access object value inside static method?

I'm using static getDerivedStateFromProps from react to conditionally update the state.我正在使用static getDerivedStateFromProps from react 有条件地更新 state。

This is the sample code:这是示例代码:

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;
        }
    }

In the above code console.log(data[0]) returns the value of data at index 0 but when I try to access the object value inside the data[0] it throws error website_id is undefined.在上面的代码中, console.log(data[0])返回索引 0 处的数据值,但是当我尝试访问 data[0] 中的 object 值时,它会抛出错误 website_id is undefined。

The structure of data array is:数据数组的结构是:

data = [{key:value, website_id...}, {key:value, website_id...}, {key:value, website_id...}, {key:value, website_id...}]

I suggest instead of using console.log() to figure out the error try using the debugger and trace each step to find out why it is undefined.我建议不要使用 console.log() 来找出错误,而是尝试使用调试器并跟踪每个步骤以找出它未定义的原因。

According to me earlier the props are empty and that's why you are not able to access the object property.根据我之前的说法,道具是空的,这就是为什么您无法访问 object 属性的原因。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM