如何在ReactJS中将JSON数组映射到列表? [英] How to map a JSON array to a List in ReactJS?

查看:119
本文介绍了如何在ReactJS中将JSON数组映射到列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在从 http://jsonplaceholder.typicode.com/users,并在ReactJS项目中使用该数组的名称值创建项目列表.

I'm requesting a sample JSON array from http://jsonplaceholder.typicode.com/users and creating a list of items using the name values of that array in a ReactJS project.

该列表是索环列表,我使用.map函数进行映射Web服务数据到每个列表项.

The list is a Grommet list and I use the .map function to map the web service data to each list item.

但是在代码呈现时,而不是使用Web服务创建名称列表.它仅创建一个列表项,并将调用呈现给.maprows.push.

But when the code renders, instead of creating a list of names using the web service. It creates only one list item and renders the call to .map and rows.push.

问题:

如何在ReactJS中将JSON数组映射到列表?

How can you to map a JSON array to a List in ReactJS?

这是我尝试过的方法,首先通过AJAX GET获取Web服务,然后调用.map将该数据映射到列表:

This is what I've tried, first getting the web service via an AJAX GET and then calling .map to map that data to a list:

loadNameData() {
    $.ajax({
      url: 'http://jsonplaceholder.typicode.com/users',
      dataType: 'json',
      success: function(data) {
        this.setState({data: data});
      }.bind(this),
      error: function(xhr, status, err) {
        console.error('#GET Error', status, err.toString());
      }.bind(this)
    });
  }

  getInitialState(){
    return {
       data: {
          names: [] 
       }
    };
  }

  componentDidMount() {
    this.loadAssetData();
  }

  render() {
      let layerNode;
      var rows = [];

      layerNode = (
        <Layer flush={true} closer={true} onClose={() => this._onCloseLayer()} align='right'>
          <Box pad='medium' colorIndex='grey-3'>
            <Heading>Filter Options</Heading>
            <Label>Names</Label>
                this.props.data.names.map(function(name) {
                    rows.push(<ListItem justify="between">)
                    rows.push(<span>)
                    rows.push({name})
                    rows.push(</span>)
                    rows.push(</ListItem>)
                }
                <List selectable={true} selected={0}>       
                    {rows}
                </List>           
          </Box>
        </Layer>
      );  

    return (
      <Section pad="small" full="vertical" flex={true}>         
                {layerNode}             
      </Section>
    );
  }

推荐答案

我在这里看到了一些问题,希望我能够解决所有问题.

I see a few problems here, hopefully I will be able to address them all.

1)我在评论中提到了这一点,但是您似乎不了解.map()应该做什么. 这里是参考.

1) I mentioned this in the comments, but it doesn't look like you understand what .map() is supposed to do. Here's a reference.

tl; dr:在一个可迭代对象上调用.map()并传递要在每个项目上执行的函数,将返回该函数的返回值的集合.

tl;dr: Calling .map() on an iterable object and passing a function to be executed on each item will return a collection of the return values of that function.

作为一个例子,考虑一个具有几个名称['Michael', 'Brian', 'John']的数组.我可以在此数组上调用.map(),并使用它返回一个字符串数组,该字符串向列表中的每个人说你好":

As an example, consider an array with a few names ['Michael', 'Brian', 'John']. I can call .map() on this array and use it to return an array of strings that say "hello" to everyone in the list:

var names = ['Michael', 'Brian', 'John'];
var sayHello = names.map(function (name) {
    return 'Hello, ' + name;
});
console.log(sayHello); // ['Hello, Michael', 'Hello, Brian', 'Hello, John'];

这可以在React中用于执行看起来像给出一些名称,返回一些代表这些名称标记的React组件"之类的逻辑.

This can be used in React to perform logic that looks something like "Given some names, return some React components that represent the markup for those names".

2)您链接的JSON数据是一个对象数组,每个对象都有自己的name属性.看起来您正在使用jQuery来获取它并将结果保存在this.state.data中.这意味着this.state.data 是一个数组.因此,如果您尝试执行this.state.data.names.map(),它将失败,因为this.state.data.names是未定义的.您将要改为this.state.data.map().

2) The JSON data you have linked is an array of objects, each with their own name property. It looks like you're using jQuery to fetch this and save the result in this.state.data. This means that this.state.data is an array. So if you try to do this.state.data.names.map(), it's going to fail, because this.state.data.names is undefined. You'll want to do this.state.data.map() instead.

3)在JSX内部,您可以执行JavaScript表达式/语句,只要它们在花括号{}中即可.看来您没有这样做.

3) Inside of JSX, you can perform JavaScript expressions/statements as long as they're within curly braces {}. It doesn't look like you're doing that.

4)您呼叫.map()是在this.props.data上,我想您想改用this.state.data.

4) Your call to .map() is on this.props.data, I think you want to do this.state.data instead.

这是我看到的所有应解决或改进的功能,然后才能按预期运行.如果是我,我会将您的.map()通话保留在您要呈现为的<List />内:

This is everything I saw that should be fixed or improved before this starts working as you expect it to. If it were me, I'd keep your .map() call inside of the <List /> that you're trying to render to:

<List selectable={true} selected={0}>       
    {
        this.state.data.map(function (person) {
            return (
                <ListItem justify="between">
                    <span>{person.name}</span>
                </ListItem>
            );
        })
    }
</List>

或者更干净的解决方案是将这种逻辑引入其自己的辅助函数中.但这并不是必须的.

Or perhaps a cleaner solution would be to pull this logic out to its own helper function. But that isn't necessary for this to work.

这是一个演示

这篇关于如何在ReactJS中将JSON数组映射到列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆