首页 > 解决方案 > Twitch api 地图功能除了控制台日志之外没有返回任何内容?

问题描述

目前我在 Nextjs 中有一个页面正在调用多个 twitch 端点,它们都可以工作并显示适当的数据,但是其中一个映射函数不会呈现任何内容,但是如果我控制台记录它的映射呢?我对使用 API 有点陌生,但这个项目很有趣,我真的很想完成它。

任何帮助都会很棒!

页面截图截屏

//pages/TwitchDash/index.js
import axios from "axios";
import {
  VStack,
  Heading,
  Divider,
  Text,
  Box,
  Badge,
  Center,
  Button,
  Flex,
  Link,
  SimpleGrid,
  Stack,
  useColorModeValue,
  HStack,
  Icon,
  chakra,
  Image,
} from "@chakra-ui/react";
import { getSession } from "next-auth/react"
import React, { useState } from "react"
// import UserCards from '../../components/topCards'
import { FaArrowRight } from 'react-icons/fa'
import { CategoryCard } from '../../components/topCards/CategoreyCard'

const Twitch = ({ TwitchLive, Sk, User }) => {
  const [showKey, setShowKey] = useState(false);
  const Show = () => setShowKey(true);
  const Hide = () => setShowKey(false);

  if (!Twitch) {
    return <div>Loading...</div>;
  }
  return (
      <>
        <VStack>
        {User?.map((us) => (
          console.log(User),
            <Box key={us.id}>
            <Center>
                <Heading p="4">{us.display_name}</Heading>
                <Badge
                fontSize="15px"
                colorScheme="purple"
                >View Count {us.view_count}
                </Badge>
            </Center>
            </Box>
        ))}
        {Sk.map((key) =>(
        <div key={key.id}>
        <Button margin={2} onClick={Show}>Show Stream Key</Button>
        <Button margin={2} onClick={Hide}>Hide Stream Key</Button>
        {showKey ? <Text>{key.stream_key}</Text> : null}
        </div>
        ))}
        </VStack>
        <Flex
      bg={useColorModeValue("#F9FAFB", "gray.600")}
      p={50}
      w="full"
      alignItems="center"
      justifyContent="center"
    >
      <Box
        maxW="xs"
        mx="auto"
        bg={useColorModeValue("white", "gray.800")}
        shadow="lg"
        rounded="lg"
      >
        <Box px={4} py={2}>      
        {TwitchLive.map((tl) => { //This function here is the error
          console.log(TwitchLive), // This console log returns the correct data you can see in the linked image.
          <div key={tl.id}>
          <a>{tl.user_name}</a> // This renders nothing along with the rest of this ?
          <chakra.h1
                color={useColorModeValue("gray.800", "white")}
                fontWeight="bold"
                fontSize="3xl"
                textTransform="uppercase"
            >
                {tl.user_name}
            </chakra.h1>
            <chakra.p
                mt={1}
                fontSize="sm"
                color={useColorModeValue("gray.600", "gray.400")}
            >{tl.description}
                </chakra.p>
                </div>
        })}
        </Box>
        {TwitchLive.map((tl) => {
        <div key={tl.id}>
        <Image
          h={48}
          w="full"
          fit="cover"
          mt={2}
          src={tl.thumbnail_url}
          alt="Twitch live stream thumbnail"
        />

        <Flex
          alignItems="center"
          justifyContent="space-between"
          px={4}
          py={2}
          bg="gray.900"
          roundedBottom="lg"
        >
          <chakra.h1 color="white" fontWeight="bold" fontSize="lg">
            {tl.viewer_count}
          </chakra.h1>
          <chakra.button
            px={2}
            py={1}
            bg="white"
            fontSize="xs"
            color="gray.900"
            fontWeight="bold"
            rounded="lg"
            textTransform="uppercase"
            _hover={{
              bg: "gray.200",
            }}
            _focus={{
              bg: "gray.400",
            }}
          >
            Add to cart
          </chakra.button>
        </Flex>
        </div>
        })}
      </Box>
    </Flex>
    </>
  );
};

Twitch.getInitialProps = async (ctx) => {
  try {
    const session = await getSession({
      req: ctx.req,
    });
    // Console log is acurate won't render to page?
    const followed = await axios.get(
      `https://api.twitch.tv/helix/streams/followed?user_id=${session.id}`,
      {
        headers: {
          "Authorization": `Bearer ${session.accessToken}`,
          "Client-Id": `${process.env.TWITCH_CLIENT_ID}`,
        },
      }
    );
    // Working Fine
    const key = await axios.get(
        `https://api.twitch.tv/helix/streams/key?broadcaster_id=${session.id}`,
        {
          headers: {
            "Authorization": `Bearer ${session.accessToken}`,
            "Client-Id": `${process.env.TWITCH_CLIENT_ID}`,
          },
        }
      );
      // Working Fine
      const Info = await axios.get(
        `https://api.twitch.tv/helix/users?id=${session.id}`,
      {
          headers: {
            "Authorization": `Bearer ${session.accessToken}`,
            "Client-Id": `${process.env.TWITCH_CLIENT_ID}`,
          },
        }
      );

    const TwitchLive = followed.data.data;
    const Sk = key.data.data;
    const User = Info.data.data;
    return { TwitchLive, Sk, User };
  } catch (error) {
    console.log(error);
    return <div>{error.message}</div>;
  }
};

export default Twitch;
// console.log(TwitchLive)
[
  {
    id: '43584848620',
    user_id: '12731745',
    user_login: 'deadlyslob',
    user_name: 'Deadlyslob',
    game_id: '470840663',
    game_name: 'The Cycle: Frontier',
    type: 'live',
    title: 'Thursday SPACE TARKOV TIME - SwampFox Joining Later - !ASUS - !NORD',
    viewer_count: 2191,
    started_at: '2021-10-21T11:08:04Z',
    language: 'en',
    thumbnail_url: 'https://static-cdn.jtvnw.net/previews-ttv/live_user_deadlyslob-{width}x{height}.jpg',
    tag_ids: [ '6ea6bca4-4712-4ab9-a906-e3336a9d8039' ],
    is_mature: false
  },
  {
    id: '43584228412',
    user_id: '63526015',
    user_login: 'bakeezy',
    user_name: 'BakeeZy',
    game_id: '509658',
    game_name: 'Just Chatting',
    type: 'live',
    title: 'BAKEEZY PLAYING TARKOV SHOCKING!!! !cheats2 !kappa !battlefield ',
    viewer_count: 509,
    started_at: '2021-10-21T07:22:25Z',
    language: 'en',
    thumbnail_url: 'https://static-cdn.jtvnw.net/previews-ttv/live_user_bakeezy-{width}x{height}.jpg',
    tag_ids: [
      '6ea6bca4-4712-4ab9-a906-e3336a9d8039',
      'a3cf86b7-90a4-409d-be29-e672c6c6e8fd'
    ],
    is_mature: false
  },
  {
    id: '44149261325',
    user_id: '72839510',
    user_login: 'redopz',
    user_name: 'RedOpz',
    game_id: '470840663',
    game_name: 'The Cycle: Frontier',
    type: 'live',
    title: 'Want some Keys?! !youtube',
    viewer_count: 177,
    started_at: '2021-10-21T06:45:41Z',
    language: 'en',
    thumbnail_url: 'https://static-cdn.jtvnw.net/previews-ttv/live_user_redopz-{width}x{height}.jpg',
    tag_ids: [ '6ea6bca4-4712-4ab9-a906-e3336a9d8039' ],
    is_mature: false
  },
  {
    id: '44151126637',
    user_id: '96061540',
    user_login: 'artesianbuilds',
    user_name: 'artesianbuilds',
    game_id: '509658',
    game_name: 'Just Chatting',
    type: 'live',
    title: "Don't sleep on these builds, or you'll regret it! || !hiring !screwdriver !youtube !website !waterbottle",
    viewer_count: 0,
    started_at: '2021-10-21T13:02:29Z',
    language: 'en',
    thumbnail_url: 'https://static-cdn.jtvnw.net/previews-ttv/live_user_artesianbuilds-{width}x{height}.jpg',
    tag_ids: [
      '6ea6bca4-4712-4ab9-a906-e3336a9d8039',
      '64d9afa6-139a-48d5-ab4e-51d0a92b22de',
      '7b49f69a-5d95-4c94-b7e3-66e2c0c6f6c6',
      'cd9ed640-426d-4a08-b8e0-417a61197264',
      'c38aeb6e-e8c7-452a-88e1-a3ed62c2e846',
      'b3d8d789-dd4d-4566-8a9b-62a182ada7d5'
    ],
    is_mature: true
  }
]

标签: javascriptapinext.jstwitch-api

解决方案


您必须return在最后一个map函数中使用,因为您在curly其中使用了括号。所以应该是

 {TwitchLive.map((tl) => { 
          console.log(TwitchLive)
          return (
          <div key={tl.id}>
          .....
          ...
          )

推荐阅读