ReactJS中props解构报错:URL路由参数取值为undefined如何解决?
问题原因
你对ESLint的react/destructuring-assignment规则要求存在理解偏差,同时忽略了路由参数的嵌套层级:
react-router v5 传给路由组件的props顶层并不包含userName属性,该属性实际嵌套在props.match.params层级下。你直接从props顶层解构userName,自然会返回undefined。
符合ESLint规则的正确写法
提供两种常用写法,均满足解构要求:
写法1:参数位嵌套解构(代码更简洁)
const ConfirmRegistrationPage = ({ match: { params: { userName } } }) => { return ( <> <h1>Congratulations, { userName }! </h1> </> ); };
写法2:函数内分层解构(可读性更高,适合多参数场景)
const ConfirmRegistrationPage = ({ match }) => { const { params: { userName } } = match; return ( <> <h1>Congratulations, { userName }! </h1> </> ); };
可选补充方案
如果你暂时不想使用嵌套解构,也可以在对应代码行上方添加注释,临时禁用该规则校验:
// eslint-disable-next-line react/destructuring-assignment const { userName } = props.match.params;
内容的提问来源于stack exchange,提问作者Tom
相关产品推荐
相关产品推荐

