繁体   English   中英

渲染对象数组React

[英]Rendering an array of objects React

下午好,

我正在尝试显示在初始渲染之前由MongoDB实例提供给我的应用程序的数据。 我仍然无法成功执行此操作,遇到了错误或警告。

这是我正在使用的render方法的一部分。

        <div className="right-column">
            <div className="pipeline">

              {this.props.tournamentList.map((x,i) => {
                return <li key={i}>{x.name}</li>
              })}

            </div>

        </div>

this.props.tournamentList具有对象数组的值,如下所示:

tournamentList:
Array[15]
0:
{…}
1:
{…}
2:
{…} ...

该列表是通过componentWillMount生命周期方法到达我的应用程序的,因此是在初始渲染之前进行的。 对我来说,我应该能够遍历数组并制作由数据库提供的动态生成的锦标赛列表。

但是使用我提供的代码,我会收到以下警告:

Uncaught (in promise) Error: Objects are not valid as a React child (found: object with keys {prelims, outRounds, notes}). If you meant to render a collection of children, use an array instead or wrap the object using createFragment(object) from the React add-ons. Check the render method of Uncaught (in promise) Error: Objects are not valid as a React child (found: object with keys {prelims, outRounds, notes}). If you meant to render a collection of children, use an array instead or wrap the object using createFragment(object) from the React add-ons. Check the render method of BuildTournament Uncaught (in promise) Error: Objects are not valid as a React child (found: object with keys {prelims, outRounds, notes}). If you meant to render a collection of children, use an array instead or wrap the object using createFragment(object) from the React add-ons. Check the render method of .

我尝试了这种方法,创建了一个名为displayTournaments并在div内部使用“管道”类对其进行了调用,但没有任何反应,没有错误,没有渲染:

displayTournaments(){

        const { tournamentList } = this.props;

        tournamentList.map((x,i) => {
                    return <li key={i}>{x.name}</li>
                  })


    }

显然我在做错事,但我不知道该怎么办。 这是错误消息所建议的应使用键控片段的实例吗? 有没有一个比我聪明的人愿意提供一些见识?

干杯。

更新:对不起,我误解了你的问题。 凯尔(Kyle)的加载状态正确。

此外,使用lodash之类的库将使您可以更自然地映射对象。 原生的javascript map方法不能很好地处理对象。

https://www.npmjs.com/package/lodash

您使用方式大致相同。 只是

import _ from lodash

然后

_.map(objectToMap, (x) => <Component key={x}>{x.thing}</Component>)

如果您在componentWillMountcomponentDidMount生命周期挂钩中获取数据,则将需要具有加载状态。 下面的示例将说明如何完成此操作。

class ComponentThatGetsAsyncData extends PureComponent {
    constructor( props ) {
        super( props );

        this.state = {
            tournamentList: [ ]
        }
    }

    componentDidMount() {
        // use any http library you choose
        axios.get( "/some_url" )
            .then( ( res ) => {
                // this will trigger a re-render
                this.setState({
                    tournamentList: res.data
                });
            })
            .catch( ( err ) => {
                // handle errors
            });
    }

    render() {
        const { tournamentList } = this.state;
        // i'd use something other than index for key

        // on your initial render your async data will not be available
        // so you give a loading indicator and when your http call
        // completes it will update state, triggering a re-render
        return (
            {
                tournamentList ?
                    tournamentList.map((x,i) => {
                        return <li key={i}>{x.name}</li>
                    }) :
                    <div className="loading">Loading...</div>
            }
        );
    }
}

这是一个简单的解决方案,具有加载状态,错误状态和成功状态。

首先要注意的是,由于无法映射普通对象,因此需要在对象上使用Object.keys()才能映射到键数组上。 还应注意的是,地图将返回每个对象的键,以便以目标键值对,你将需要使用像这样的语法tournaments[key].name ,而不是仅仅做tournament.name为您的目标对象在一个对象中,然后获取值。

让我知道您是否需要更多帮助

import React from 'react'
import Loader from '../Loader'

const resultList = ({ tournaments, isFetching = true }) => (
<div>
    {
        isFetching
            ?   <div>
                    <Loader /><br />
                    <span>Loading&hellip;</span>
                </div>
            :   <div>
                    {
                        Object.keys(tournaments).length
                        ?   <div>
                                {
                                  tournaments.map((key) => (
                                        <section id={tournaments[key].id} key={key}>
                                            <p>{tournaments[key].name}</p>
                                        </section>
                                    ))
                                }
                            </div>
                        :   <div>
                                <p>There are no tournaments....</p>
                            </div>
                    }
                </div>
    }
</div>
);

export default resultList

暂无
暂无

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

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