简体   繁体   English

将对象传递给子反应组件的问题

[英]Issue with passing object to child react componenet

I am using react, currently I need to display a html list, in LocationFinderList I am initializing Location elements but Location does not get the object and instead I get only numeric property as shown in the pictures. 我正在使用react,目前我需要显示一个HTML列表,在LocationFinderList我正在初始化Location元素,但是Location没有获得对象,而是仅获得了数字属性,如图所示。

How to fix my script so Location show the name for an object passe from LocationFinderList`? 如何修复我的脚本,以便“ Location show the name for an object passe from

Could be an issue with spread operator? 传播操作员可能会遇到问题吗?

Notes: location in locations object in LocationFinderList are defined as properties of an object not as items in an array. 注意:LocationFinderList中的locations对象中的LocationFinderList被定义为对象的属性,而不是数组中的项。


{
                2643743: {
                    name: "London",
                    country: "GB"
                },
                4119617: {
                    name: "London",
                    country: "US"
                }
}

import React, { PropTypes } from 'react';
import Location from './Location';

const LocationFinderList = ({ locations, onLocationClick }) => (
    <ul>
        {Object.keys(locations).map((location, index) =>
            <Location
                key={index}
                {...location}
                onClick={() => onLocationClick(location.id)}
            />
        )}
    </ul>
);

export default LocationFinderList;

import React, { PropTypes } from 'react';

const Location = ({ onClick, location }) => (
    <li
        onClick={onClick}
    >
        {location}
    </li>
)

export default Location;

在此处输入图片说明

Since you are using Object.keys to map over you will get the keys as a result and hence if you want to pass the object you need to pass it like locations[location] 由于您正在使用Object.keys进行映射,因此您将获得键,因此,如果您要传递对象,则需要像locations[location]一样传递它

Change you code to 将您的代码更改为

const LocationFinderList = ({ locations, onLocationClick }) => (
    <ul>
        {Object.keys(locations).map((location, index) =>
            <Location
                key={index}
                {...locations[location]}
                onClick={() => onLocationClick(location)}
            />
        )}
    </ul>
);

And

const Location = ({ onClick, name, country}) => (
    <li
        onClick={onClick}
    >
        {name}
    </li>
)

Change {...locations} 更改{...位置}

to {...locations[location]} 到{... locations [location]}

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

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