【问题标题】:can't find variable name when its inside an if statement在 if 语句中找不到变量名
【发布时间】:2020-10-08 14:36:22
【问题描述】:

运行 graphql 查询后,我从结果中提取一些值到一个对象中,并在我的平面列表中使用它。

const DATA = data.users.nodes[0].userRelations.map(
      (item: { relatedUser: { firstName: string; id: number } }) => ({
        id: item.relatedUser.id,
        imageUrl: defaultUrl,
        name: item.relatedUser.firstName,
      }),
    );

这行得通。但是,当我将其更改为以下内容时:

  const { error, data, refetch } = useUsersQuery({
    variables: {
      where: { id: 1 },
    },
  });

  if (data) {
    const DATA = data.users.nodes[0].userRelations.map(
      (item: { relatedUser: { firstName: string; id: number } }) => ({
        id: item.relatedUser.id,
        imageUrl: defaultUrl,
        name: item.relatedUser.firstName,
      }),
    );
  } else {
    const DATA = [
      {
        id: 'bd7acbea-c1b1-46c2-aed5-3ad53abb28ba',
        imageUrl: defaultUrl,
        name: 'Johann',
      },
      {
        id: '3ac68afc-c605-48d3-a4f8-fbd91aa97f63',
        imageUrl: defaultUrl,
        name: 'Lars',
      },
      {
        id: '58694a0f-3da1-471f-bd96-145571e29d72',
        imageUrl: defaultUrl,
        name: 'Sarah',
      },
    ];
  }


...
<FlatList
          data={DATA}
          horizontal={true}
          scrollEnabled
          renderItem={({ item }) => (
            <WhitelistItem title={item.name} face={item.imageUrl} />
          )}
          keyExtractor={(item) => item.id}
        />

我在这里开始遇到错误data={DATA} Cannot find name 'DATA'. Did you mean 'data'?。为什么会这样?即使查询失败,我仍然在 else 语句中创建一个 DATA 变量。那么为什么这里没有被检测到呢?我该如何解决这个问题?

【问题讨论】:

    标签: javascript reactjs typescript react-native react-native-flatlist


    【解决方案1】:
      let DATA;
      if (data) {
        DATA = data.users.nodes[0].userRelations.map(
          (item: { relatedUser: { firstName: string; id: number } }) => ({
            id: item.relatedUser.id,
            imageUrl: defaultUrl,
            name: item.relatedUser.firstName,
          }),
        );
      } else {
        DATA = [
          {
            id: 'bd7acbea-c1b1-46c2-aed5-3ad53abb28ba',
            imageUrl: defaultUrl,
            name: 'Johann',
          },
          {
            id: '3ac68afc-c605-48d3-a4f8-fbd91aa97f63',
            imageUrl: defaultUrl,
            name: 'Lars',
          },
          {
            id: '58694a0f-3da1-471f-bd96-145571e29d72',
            imageUrl: defaultUrl,
            name: 'Sarah',
          },
        ];
      }
    

    letconst 是块作用域,这意味着它们没有在声明它们的块(大括号)之外定义。当您在 if/else 中声明 DATA 时,它只会在其中声明。

    【讨论】:

      猜你喜欢
      • 2018-05-09
      • 1970-01-01
      • 1970-01-01
      • 2023-03-19
      • 1970-01-01
      • 1970-01-01
      • 2019-03-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多