首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >TypeError:无法读取null的属性“experience”(reactJS)

TypeError:无法读取null的属性“experience”(reactJS)
EN

Stack Overflow用户
提问于 2021-04-16 17:07:57
回答 2查看 158关注 0票数 1

我是一名学生,正在学习ReactJS构建网络应用程序,我遇到了这个错误的问题。

代码语言:javascript
复制
router.post('/experience', passport.authenticate('jwt', { session: false }), (req, res) => {
    const { errors, isValid } = validateExperienceInput(req.body);

//Check Validation
if (!isValid) {
    //Return any errors with 400 status
    return res.status(400).json(errors);
}

Profile.findOne({ user: req.user_id })
    .then(profile => {
        const newExp = {
            title: req.body.title,
            company: req.body.company,
        }
        //Add to experience array
        //There is the error generated
        profile.experience.unshift(newExp);
        profile.save().then(profile => res.json(profile));
    })
});

下面是一个配置文件模型,其中声明了经验数组

代码语言:javascript
复制
const ProfileSchema = new Schema({
user: {
    type: Schema.Types.ObjectId,
    ref: 'users'
},
handle: {
    type: String,
    required: true,
    max: 40
},
experience: [
    {
        title: {
            type: String,
            required: true
        },
        company: {
            type: String,
            required: true
        },
    }
],
});

这就是我得到的错误

代码语言:javascript
复制
(node:14580) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'experience' of null
at C:\Users\HP 840 G3\Desktop\LinkedIn\routes\api\profile.js:180:21
at processTicksAndRejections (internal/process/task_queues.js:93:5)

我在Windows 10专业版上使用Visual Studio代码,并使用Postman Web测试应用程序

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2021-04-16 17:27:49

profile.experience.unshift(newExp)此行将导致错误(除非它是由您没有发布的代码引起的)。

可能的原因是您的findOne实际上没有"findOne“并且返回了undefined。

您可以添加一个if

代码语言:javascript
复制
Profile.findOne({ user: req.user_id })
    .then(profile => {
        if (!profile) return
        const newExp = {
            title: req.body.title,
            company: req.body.company,
        }
        //Add to experience array
        //There is the error generated
        profile.experience.unshift(newExp);
        profile.save().then(profile => res.json(profile));
    })
});

或任何等效的代码。

票数 1
EN

Stack Overflow用户

发布于 2021-04-16 17:27:53

参数profile为null。您需要将对象传递给Promise定义findOne中的resolve方法(上面没有显示)。示例:

代码语言:javascript
复制
let findOne = new Promise(function(resolve, reject) {
  let resolveParam = { experience: [] };
  setTimeout(() => resolve(resolveParam), 1000);
});
findOne.then(
  profile => console.log(profile)
);

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/67122328

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档