Gatsby:TypeError:无法读取null的属性“ map”

时间:2019-10-06 10:56:53

标签: javascript gatsby contentful

我在盖茨比(Gatsby)应用程序中收到此错误,该错误为Author拉出位置数据。该错误显示author.social的map()点为空

TypeError: Cannot read property 'map' of null

我已经尝试提供默认值,但是它似乎不起作用

这是默认代码:

authors: ({ node: author }) => {
    return {
      ...author,
      social: author.social.map(s => ({ url: s })),
    };
  },

这是我的改变:

authors: ({ node: author }) => {
      return {
        ...author,
        social: author.social.map(s => {
          if (s === null) {
            return ({ url: 'https://www.mywebsite.com' });
          } else {
            return ({ url: s });
          }
        })
        ,
      };
    },

任何帮助都将非常有帮助,

谢谢

1 个答案:

答案 0 :(得分:1)

这就是为什么我会这样做:

authors: ({ node: author }) => {
    // This to inspect what there is inside the variable 
    console.log(author);
    // And something like this to avoid the error:
    if(author.social && author.social.length > 0){
      // code here
    }
  });