简体   繁体   English

JavaScript Map.get(variableName) 返回 undefined

[英]JavaScript Map.get(variableName) is returning undefined

I am using react router to pass an Id via the URL parameter and setting my variable like let { posterId } = useParams();我正在使用 react router 通过 URL 参数传递 Id 并设置我的变量,例如let { posterId } = useParams();

This seems to be working as expected because I can write it out in the JSX just fine <h1> This is a specific poster {posterId}</h1>这似乎按预期工作,因为我可以在 JSX 中写出来就好了<h1> This is a specific poster {posterId}</h1>

However, when I try to use it to get from a map that I am passing via props it returns undefined from the map props.postersMap.get(posterId) .但是,当我尝试使用它从我通过 props 传递的地图获取时,它从地图props.postersMap.get(posterId)返回 undefined 。

I verified that the map is populated and if I hard code the .get method to the variable value it works as expected.我验证了地图已填充,如果我将 .get 方法硬编码为变量值,它会按预期工作。 Is there something I am just overlooking?有什么我只是忽略了吗?

Edit: full component code编辑:完整的组件代码

import React from 'react'
import { useParams} from 'react-router-dom'

export default function Poster(props) {
    let { posterId } = useParams();

    return (
        <div>
            {console.log(props.postersMap)}
            {console.log(posterId)}
            {console.log(props.postersMap.get(posterId))}
            {props.postersMap.get(posterId) ? <p>{props.postersMap.get(posterId).band}</p> : <p></p>}

        </div>
    )
}

Here is what my console.logs are showing这是我的 console.logs 显示的内容

在此处输入图片说明

The js Map keys must match exactly: if keys are numbers (and they are in your case), then you retrieve them using numeric values. js Map键必须完全匹配:如果键是数字(在您的情况下是),则您可以使用数字值检索它们。

props.postersMap.get(Number(posterId)) would do. props.postersMap.get(Number(posterId))就可以了。

Or guarantee you're providing a valid numeric any other available way.或者保证您以任何其他可用的方式提供有效的数字。

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

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