简体   繁体   English

将 props 传递到 React 组件(TypeScript、React 和 Next.js)时映射函数不起作用

[英]Map function not working while passing props into React component (TypeScript, React and Next.js)

I'm new to TypeScript and Next.js.我是 TypeScript 和 Next.js 的新手。 I've created an index page that gets the JSON data from the mock database and after it's returned, it is supposed to dynamically create a new Block component for each object in the array using the map function.我创建了一个索引页面,它从模拟数据库中获取 JSON 数据,在它返回后,它应该使用 map 函数为数组中的每个对象动态创建一个新的 Block 组件。

I know that the Block component outside of the map function displays but doesn't seem to be calling the Block component while running the map function.我知道 map 函数之外的 Block 组件显示但在运行 map 函数时似乎没有调用 Block 组件。 Any ideas?有任何想法吗?

This is my index page:这是我的索引页:

import fetch from 'isomorphic-unfetch';

import {Block} from 'components/text/block';


interface Props {
  games: [{
    _id: string;
    name: string;
  }]
}

const Home: NextPage<Props> = ({games}) => {
  console.log(games);

  return (
  <div>
    {games.map((g) => {
      console.log("Inside Map " + JSON.stringify(g.name));
      <Block key={g._id} name={g.name}></Block>
    })}
    <Block key={games[0]._id} name={games[0].name}></Block>
  </div>
  )
};

Home.getInitialProps = async () => {
  const response = await fetch('http://localhost:3000/api/games')
  const games = await response.json();
  return {games};
};

export default Home;

This is my Block component:这是我的 Block 组件:

import React from 'react';

interface Props {
  name: string;
  key: string;
}

export let Block: React.FC<Props> = ({name}) => {
  console.log("JSX Block " + name);
  return (
    <div>
      <h1>{name}</h1>
    </div>
  )
}

you are not returning anything from inside the map thus (implicit) undefined gets returned and renders nothing.您没有从地图内部返回任何内容,因此(隐式) undefined被返回并且不渲染任何内容。 you need to return your Block JSX element.您需要返回Block JSX 元素。

{games.map((g) => {
  console.log("Inside Map " + JSON.stringify(g.name));
  return <Block key={g._id} name={g.name}></Block>   // <----------------------
})}

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

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