简体   繁体   English

在React状态下使用嵌套对象

[英]Using nested objects in React state

Objects are not valid as a React child (). 对象作为React子对象()无效。 If you meant to render a collection of children, use an array 如果要渲染子级集合,请使用数组

I receive the above error and I don't fully understand the limitations of what it's telling me. 我收到上述错误,但我不完全理解它所传达的限制。 Here is my code that is giving me this error, I have an object where one of the properties has the value of an array of objects: 这是给我这个错误的代码,我有一个对象,其中一个属性具有对象数组的值:

state = {
    clubs: [{
        teamName: something,
        gamesPlayed: [{
            homeTeam: someName,
            awayTeam: someNameElse,
            score: numbers
        },
        {
            homeTeam: ...
            ... etc
        }]
    }]
}

The element that renders the code: 呈现代码的元素:

function RenderTest(props) {
    return (
        <ul>
            <li>
                <div>
                    <ul style={{paddingLeft: 10+'px'}}>
                        {props.clubs.map( (key, i) => (
                            <li>
                                <div>Team: {key.teamName} ID: {key.teamId}</div> <-- works as expected
                                <div>Games Played: {key.gamesPlayed.home}</div> <-- throws the error
                            </li>
                        ))}
                    </ul>
                </div>
            </li>
        </ul>
    )
}

Does it mean that I cannot have a nested object like this? 这是否意味着我不能有这样的嵌套对象? It seems a bit limiting. 似乎有点限制。 It seems logical that I store the data like this - clubs is an array of objects, each one a football team with their games played that season. 我这样存储数据似乎是合乎逻辑的-俱乐部是一组对象,每个对象都是一支足球队,他们在那个赛季打过比赛。

Thank you 谢谢

When you write 当你写

<div>Games Played: {key.gamesPlayed.home}</div>

you basically tell react to create a div element with exactly two children: 您基本上可以告诉react创建具有两个孩子的div元素:

  1. The string 'Games Played: ', 字符串“ Games Played:”,
  2. Whatever key.gamesPlayed.home stores, in this case it is an array (Which is basically just an object in javascript)! 无论key.gamesPlayed.home存储什么,在这种情况下,它都是一个数组 (基本上只是javascript中的一个对象)!

React on the other side requires, that children of any components must be either a string or another component. 另一方面,React要求任何组件的子代必须是字符串或其他组件。 An array is none of that. 数组并非如此。 So in order to make it work, you have to loop over the array and render the respective part of each array element. 因此,为了使其工作,您必须遍历数组并呈现每个数组元素的相应部分。 A short example from my side to replace above code snipped would be 从我这边替换上面的代码的简短示例是

<div>
  {key.gamesPlayed.map(game => (
    <div>{game.homeTeam}</div>
  )}
</div>

(Assuming game.homeTeam is a string!) (假设game.homeTeam是一个字符串!)

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

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