Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
264 views
in Technique[技术] by (71.8m points)

javascript - JavaScript Map.get(variableName)返回未定义(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();(我正在使用let { posterId } = useParams(); 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)返回未定义。) 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.log显示的内容) 在此处输入图片说明   ask by Cogorlopez translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.(或保证您以任何其他可用的方式提供有效的数字。)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...