简体   繁体   English

如何使用ReactJS中的组件加载列表数据?

[英]How can load data of lists using component in ReactJS?

I am trying to render some data using 'ListItem' component in ReactJS. 我正在尝试使用ReactJS中的'ListItem'组件渲染一些数据。 But the component is not getting the data. 但是组件没有获取数据。 I also tried to load the data without using 'ListItem' component. 我还尝试不使用“ ListItem”组件加载数据。 In that case it is successfully rendering. 在这种情况下,它可以成功渲染。

So, How can i load the data using 'ListItem' component? 那么,如何使用“ ListItem”组件加载数据?

import React, { Component } from 'react';

function ListItem(props) {
  console.log(props);
  return <li>{props.value}</li>;
}

class NumberList extends Component {
  constructor(props) {
    super(props);
  }

  render() {
    const numbers = this.props.numbers;

    const listItems = numbers.map( (number) => {
      <ListItem key={number.toString()} value={number} />
    });

    console.log(listItems);
    return(
      <ul>
        {
        // numbers.map( n => {
        //   return <li>{n}</li>
        // } ) 
        listItems
        }
      </ul>
    );
  }
}

export default NumberList;

You are returning undefined in your map -function. 您将在map函数中返回undefined

Try changing to this: 尝试更改为此:

const listItems = numbers.map( (number) => {
  return <ListItem key={number.toString()} value={number} />
}); 

or: 要么:

// By omitting the {} around the callback function body
// you can utilise the implicit-returning feature of arrow functions.
const listItems = numbers.map( (number) => (
  <ListItem key={number.toString()} value={number} />
));

// The above example is the same as:
const listItems = numbers.map( (number) => <ListItem key={number.toString()} value={number} />);

You are using the arrow function notation inside the map. 您正在使用地图内部的箭头功能表示法。 When you use it with braces ({ and }), you should add a return to the statement you wish to return. 当将其与大括号({和})一起使用时,应在要返回的语句中添加一个return。

const add = (a, b) => {
    return a + b;
};

When your function has just one statement, you can omit the braces and place only the statement at the right side of the arrow, like this: 当您的函数只有一个语句时,您可以省略花括号并将其仅放置在箭头的右侧,如下所示:

const add = (a, b) => a + b;

But if you add the braces, but does not write a return statement, then the function will return undefined. 但是,如果您添加括号,但未编写return语句,则该函数将返回未定义。 So, this would return undefined: 因此,这将返回undefined:

const add = (a, b) => {
    const sum = a + b;
};

You have to return your listitem component from map. 您必须从地图返回您的listitem组件。 You are returning li items in your commented code. 您正在注释的代码中返回li项目。 But looks like you missed adding return when converting it to use ListItem. 但是看起来您在将其转换为使用ListItem时错过了添加返回值。

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

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