繁体   English   中英

如何修复javascript中的“无法读取null的属性'id'”错误?

[英]How to fix "Cannot read property 'id' of null" error in javascript?

我正在关注阿波罗教程。 最终结果是一个交互式应用程序,允许登录用户在即将到来的 Space-X 发射中保留一个位置。

我刚刚写完三个突变解析器:login、bookTrips 和 cancelTrip。 https://www.apollographql.com/docs/tutorial/resolvers.html#mutation

使用包含 3 个 ID 的对象数组作为参数测试 bookTrips 会导致错误。 https://graphqlbin.com/v2/K1V7ir

测试登录解析器工作https://graphqlbin.com/v2/K1V7ir

测试cancelTrip工作https://graphqlbin.com/v2/K1V7ir

我已经检查了我的代码几次寻找一个错字。 我注释掉了我的代码版本并复制/粘贴了教程中给出的代码仍然得到相同的错误。

在 src/resolvers.js 里面

bookTrips: async (_, { launchIds }, { dataSources }) => {
        const results = await dataSources.userAPI.bookTrips({ launchIds });
        const launches = await dataSources.launchAPI.getLaunchesByIds({
            launchIds,
        });

        return {
            success: results && results.length === launchIds.length,
            message: results.length === launchIds.length
                ? 'trips booked successfully'
                : `the following launches could not be booked: ${launchIds.filter(
                    id => !results.includes(id),
                )}`,
            launches,
        };
    },
cancelTrip: async (_, { launchId }, { dataSources }) => {
        const result = dataSources.userAPI.cancelTrip({ launchId });

        if (!result) 
            return {
                success: false,
                message: 'failed to cencel trip',
            };

        const launch = await dataSources.launchAPI.getLaunchById({ launchId });
        return {
            success: true,
            message: 'trip cancelled',
            launches: [launch],
        };
    },
},

在 src/datasources/launch.js 里面

// returns several launches based on their respective launchIds
getLaunchByIds({ launchIds }) {
    return Promise.all(
        launchIds.map(launchId => this.getLaunchById({ launchId })),
    );
}

// method takes in a flight number and returns the data for a particular launch
    async getLaunchById({ launchId }) {
        const res = await this.get('launches', { flight_number: launchId });
        return this.launchReducer(res[0]);
    }

// transform launch data into a shape the schema expects
    launchReducer(launch) {
        return {
            id: launch.flight_number || 0,
            cursor: `${launch.launch_date_unix}`,
            site: launch.launch_site && launch.launch_site.site_name,
            mission: {
                name: launch.mission_name,
                missionPatchSmall: launch.links.mission_patch_small,
                missionPatchLarge: launch.links.mission_patch,
            },
            rocket: {
                id: launch.rocket.rocket_id,
                name: launch.rocket.rocket_name,
                type: launch.rocket.rocket_type,
            },
        };
    }

在 src/datasources/user.js 里面

 // Takes an object with an array of launchIds and books them for the logged in user
 async bookTrips({ launchIds }) {
  const userId = this.context.user.id;
   if (!userId) return;

   let results = [];

// for each launch id, try to book the trip and add it to the results array
// if successful
for (const launchId of launchIds) {
  const res = await this.bookTrip({ launchId });
  if (res) results.push(res);
}

return results;

}

在我的 graphql 操场上运行这个之后

 mutation BookTrips {
  bookTrips(launchIds: [67,68,69]) {
   success
   message
   launches {
    id
   }
  }
 }

我期待成功消息以及我刚刚预订的突变的 ID。

好像没有找到用户。 尝试改变

async bookTrips({ launchIds }) {
    const userId = this.context.user.id;

async bookTrips({ launchIds }) {
    const userId = this.context.user && this.context.user.id;

仅供参考,当我尝试使用 Apollo 在标头中发送授权参数时遇到了同样的错误,例如:

  const currentUserJSON = localStorage.getItem("currentUser") || undefined;
  const currentUser =
    currentUserJSON !== undefined ? JSON.parse(currentUserJSON) : undefined;
  return {
    headers: {
      ...headers,
      ...(currentUser !== undefined
        ? { [`Authorization-User-ID`]: currentUser.id }
        : {}),
    },
  };
});

原来的错误是我正在检查 localStorage 是否返回 undefined,当它返回 null 时没有数据。

因此,当 currentUser 为null时,我的逻辑试图读取currentUser.id

简单的解决方案:

// Cast nulls to undefined when fetching from localStorage
localStorage.getItem("currentUser") || undefined;

暂无
暂无

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

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