【问题标题】:Destructuring props in ReactJS在 ReactJS 中解构 props
【发布时间】:2021-12-19 22:32:52
【问题描述】:

我在排查 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"
  }
}

【问题讨论】:

  • 你需要解构props.match.params => props 是一个带有match 属性的object,它是一个带有@ 的object 987654331@ 属性,它是一个具有userName 属性的对象。所以应该是const ConfirmRegistrationPage = ({ match: { params: { userName } } }) =&gt; {...} 阅读article 了解嵌套对象解构示例。
  • @MattCarlotta 此解决方案有效。的确,在我看来这很奇怪。无论如何,感谢您的解决方案。
  • 或者你可以关闭规则。 const { userName } = props.match.params; 便于阅读。

标签: javascript reactjs eslint react-props


【解决方案1】:

编辑道具解构。我会选择第一个变体。它更具可读性。

// 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>
        </>
    );
};

【讨论】:

    猜你喜欢
    • 2019-02-02
    • 2020-09-15
    • 1970-01-01
    • 2020-09-27
    • 1970-01-01
    • 1970-01-01
    • 2021-09-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多