首页 > 解决方案 > 在 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"
  }
}

标签: javascriptreactjseslintreact-props

解决方案


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

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

推荐阅读