映射

时间:2017-09-20 08:20:04

标签: javascript reactjs

我为我的应用创建了一个假的有效负载数据,我正在测试使用map()函数来完成有效负载。然而,虽然我可以在映射一些数据后返回正确数量的div,但我无法找到返回有效负载ID的正确配置。我做错了什么?

数据库看起来像这样:

export default [
{
    payloadId: 0,
    drugsId:[0, 29],
    lat: 51.760549449821696,
    lon: 19.403501300000016
},
{
    payloadId: 1,
    drugsId:[3],
    lat: 52.760549449821696,
    lon: 17.403501300000016
},
{
    payloadId: 2,
    drugsId:[5, 19, 14, 31],
    lat: 53.760549449821696,
    lon: 29.403501300000016
},
{
    payloadId: 3,
    drugsId:[3, 9],
    lat: 53.760549449821696,
    lon: 16.403501300000016
}
]

我在其中呈现随机有效负载的反应组件如下所示(所有正确的数据都从父项传递):

import React from 'react';

class WherepothecaryPanel extends React.Component{
render(){

    const fakePayload = this.props.fakePayload;

    const rngPayloadId = Math.floor(Math.random()*4);


    console.log('Random payload id', rngPayloadId)


    const payload = fakePayload.map(payload =>{
        if(payload.payloadId === rngPayloadId){
           return payload.drugsId.map(drug => {
               return <div> Drug ID: {drug.drugsId}, lat: {payload.lat}, lon: {payload.lon} </div>
           })
        }
    })

    return(
        <div>
            <div id='wherepothecaryPanel' className='col-xs-8'>
                {payload}
            </div>
        </div>
    )
}
}

export default WherepothecaryPanel

在此配置中,我的返回看起来像这样:

Drug ID: , lat: 51.760549449821696, lon: 19.403501300000016
Drug ID: , lat: 51.760549449821696, lon: 19.403501300000016

1 个答案:

答案 0 :(得分:5)

尝试:

 const payload = fakePayload.map(payload =>{
    if(payload.payloadId === rngPayloadId){
       // you are mapping through ids, so just have to use as value {id}
       return payload.drugsId.map(id => {
           return <div> Drug ID: {id}, lat: {payload.lat}, lon: {payload.lon} </div>
       })
    }
})