javascript - 在 ReactJS 中解构 props
问题描述
我在排查 EsLint 错误时遇到问题
ESLint: Must use destructuring props assignment (react/destructuring-assignment)
。
linter 需要解构道具,但如果我这样做,我会得到一个未定义的参数。
在我的代码中,我试图从 URL 获取参数。我究竟做错了什么?
这里我指出 URL 中应该包含哪些参数:
<Route path="/confirm-register/:userName?" component={ConfirmRegistrationPage} />
我的原始代码,它按预期工作,userName
参数获取一个字符串值:
strong textconst ConfirmRegistrationPage = (props) => {
const { userName } = props.match.params;
return (
<>
<h1>Congratulations, {userName}! </h1>
</>
);
};
我已经尝试过。在这种情况下,用户名未定义:
strong textconst ConfirmRegistrationPage = ({ userName }) => {
return (
<>
<h1>Congratulations, { userName }! </h1>
</>
);
};
eslint 设置:
{
"env": {
"browser": true,
"commonjs": true,
"es6": true
},
"extends": [
"plugin:react/recommended",
"plugin:react/jsx-runtime",
"eslint-config-airbnb"
],
"parserOptions": {
"sourceType": "module",
"ecmaFeatures": {
"jsx": true
},
"ecmaVersion": 11
},
"plugins": [
"react"
],
"rules": {
"react/jsx-filename-extension" : "off",
"react/prop-types": "off",
"import/no-named-as-default": "off",
"import/no-named-as-default-member": "off",
"react/jsx-one-expression-per-line": "off"
}
}
解决方案
编辑道具解构。我会选择第一个变体。它更具可读性。
// first variant
strong textconst ConfirmRegistrationPage = ({ match }) => {
const { userName } = match.params
return (
<>
<h1>Congratulations, { userName }! </h1>
</>
);
};
// second variant
strong textconst ConfirmRegistrationPage = ({ match: { params: { userName } } }) => {
return (
<>
<h1>Congratulations, { userName }! </h1>
</>
);
};
// third variant
strong textconst ConfirmRegistrationPage = ({ match: { params } }) => {
const { userName } = params
return (
<>
<h1>Congratulations, { userName }! </h1>
</>
);
};
推荐阅读
- jersey - @XmlTransient 不适用于 Json
- java - Kotlin:在内部使用可变时从 getter 返回不可变集合
- c++ - Xcode,SFML 错误 dyld:未加载库
- javascript - Node JS请求和cheerio HTML页面错误
- python-3.x - 使用 Keras 进行多处理 - 张量不是该图的元素
- android - 使用 bundle 将值从活动传递到适配器
- javascript - A-Frame appendChild 适用于 Firefox 但不适用于 Chrome
- android - 将 GCM 应用程序转换为 Firebase 问题
- php - 在另一个二维数组中搜索数组
- ios - 内部有模型时如何在可编码中使用init方法?