如何从函数调用中渲染React子组件?

时间:2019-09-20 04:41:15

标签: javascript reactjs components render react-component

我正在尝试在我的App组件中调用函数rows(),该函数将呈现PhoneBook子组件:

import React from 'react';
import PhoneBook from './components/PhoneBook';

const App = () => {
  const rows = () => {
    personsToShow.map(person => 
      <PhoneBook key={personsToShow.length+1} name={person.name} number={person.number}/>
    );
  }

  return (     
    <div>
      {rows()}
    </div>
  )
}

personsToShow是一个包含以下内容的数组:

0: {name: "Arto Hellas", number: "000-000-0000"}
1: {name: "Ada Lovelace", number: "39-44-5323523"}
2: {name: "Dan Abramov", number: "12-43-234345"}
3: {name: "Mary Poppendieck", number: "39-23-6423122"}

PhoneBook子组件定义为:

import React from 'react';

const PhoneBook = ({name, number}) => {
    return (
        <div>{name} {number}</div>
    );
}

export default PhoneBook;

为什么不呈现PhoneBook子组件?

3 个答案:

答案 0 :(得分:4)

我认为您只是忘记了从函数返回,

const rows = () => {
  //return here
  return personsToShow.map(person => 
    <PhoneBook key={person.number} name={person.name} number={person.number}/>
  );
}  

Demo

注意:您应该提供唯一的key。您的密钥在这里不是唯一的,您可以将数字(通常是唯一的)用作key={person.number}

答案 1 :(得分:2)

在箭头函数中省略{}以返回表达式。

  const rows = () =>
    personsToShow.map(person => 
      <PhoneBook key={personsToShow.length+1} name={person.name} number={person.number}/>
    );

答案 2 :(得分:1)

不要使用功能,请使用变量,因为匿名函数将在每次重新渲染时创建

import React from 'react';
import PhoneBook from './components/PhoneBook';

const App = () => {
  const rows = personsToShow.map((person, index) => // removeed function
     <PhoneBook key={index} name={person.name} number={person.number}/>
     //__________^ use proper key
  );


  return (     
    <div>
      {rows} // removed function call
    </div>
  )
}